Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Firebase Cloud Messaging - django - How to set up service worker?
I am having trouble getting firebase-messaging-sw.js to work. I would greatly appreciate any help! Thanks in advance! I'm using django with fcm-django. I tried serving the javascript as a static file, but it needs to be served from the root localhost:8000/firebase-messaging-sw.js. I tried a solution that suggested putting the following in my urls.py: url(r'^(?!/static/.*)(?P<path>.*\..*)$', RedirectView.as_view(url='/static/%(path)s')) That returns an error saying that the service worker can't be behind a redirect. I set up a view: class ServiceWorkerView(View): def get(self, request, *args, **kwargs): return render(request, 'fcmtest/firebase-messaging-sw.js') With the following line in my urlconf to hack the url: path('firebase-messaging-sw.js', views.ServiceWorkerView.as_view(), name='service_worker') Then it complains that the content-type is text/plain So I changed the view to: class ServiceWorkerView(View): def get(self, request, *args, **kwargs): return render(request, 'fcmtest/firebase-messaging-sw.js', content_type="application/x-javascript") And the error I get is: Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. My firebase-messaging-sw.js (note none of the console.log statements print): importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js"); importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-messaging.js"); importScripts("https://www.gstatic.com/firebasejs/5.2.0/init.js"); // Initialize Firebase var config = { apiKey: "AIzaSyBOb5gh1Lry84116M1uvAS_xnKtcWUoNlA", authDomain: "pyfcm-5f794.firebaseapp.com", databaseURL: "https://pyfcm-5f794.firebaseio.com", projectId: "pyfcm-5f794", storageBucket: "pyfcm-5f794.appspot.com", messagingSenderId: "813943398064" }; console.log('in service worker - before initializeApp') firebase.initializeApp(config); console.log('in service worker - after initializeApp') const messaging = firebase.messaging(); console.log('in … -
Jupyter Notebook Database Example Code into Django Framework
I've been working in a Jupyter notebook and have code that creates an SQLite3 database, manipulates data in a dataframe and modifies data in the database. I've just got it working and now I have to fit it into the Django framework for a web app I'm working on. The problem is, I don't know where to put the code in the Django project. I don't know wether it should be in a model.py or a view.py or something else? The segments in my Jupyter notebook are as follows 1: Imports (pandas,sqlite3,numpy,requests) 2: Function (addRow to database tabel) 3: Function (updateRow) 4: Setup Database Table (conn, cursor & execute sql to setup table) 5: Load data into Pandas dataframe from Excel 6: Function (analyse dataframe and update database via functions addRow & updateRow I'm really sorry for the vague question, I'm just not really sure where this logic sits in Django? The idea is to get a html page displaying dataframes populated from basic sql queries, what im using at the moment is result = pd.read_sql_query("SELECT * FROM Orders WHERE State='New';",conn) I've read somewhere about telling Django about the model but stating its unmanaged. So would the create database code … -
django migration large file
I am trying to do a makemigration on a large models.py file with hundreds of classes? The "manage.py makemigration " command is giving me a MemoryError message. I think it has to do with the large models.py file. File "/home/venv_two/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 231, in write_migration_files migration_string = writer.as_string() File "/home/venv_two/local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 166, in as_string items["operations"] = "\n".join(operations) + "\n" if operations else "" MemoryError -
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value
I'm new to Django and AWS. I was using Windows command line to work on something but I had some troubles and I tried to switch Linux subsystem now but there are actually new problems I've never seen on Windows command line. Originally I was trying to set up db on AWS but now I cannot even run local server on Linux subsystem. When I was working on Windows command line, I can run local server btw. This error causes when I try to do anything like migrate, eb deploy django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME', ''), 'USER': os.environ.get('DB_USERNAME', ''), 'PASSWORD': os.environ.get('DB_PASSWORD', ''), 'HOST': os.environ.get('DB_HOSTNAME', ''), 'PORT': os.environ.get('DB_PORT', ''), } } I'm trying to use elephantsql instead of using RDS because I cannot even connect to RDS. I already set a bunch of environment variables. I have no idea the error causes. How can I fix this error? -
Could not parse the remainder: '!=None' from '!=None' | Django Admin
Previously static files stopped working on Django Admin (pages were unstyled), but after i logged out from admin it started giving out this error on Sign-In page: Could not parse the remainder: '!=None' from '!=None'. error on sin-in django-admin: See screenshot settings.py """ Django settings for ucodin_web_app project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # 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/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'h_ipm50aodqptweir*e3v4!#82%9i!l#6uuxo=w@7v&8ims*7v' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'articles', 'quizzes', 'tutorials', 'channels', 'lib', ] 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 = 'ucodin_web_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates', ], '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', ], }, }, ] WSGI_APPLICATION = 'ucodin_web_app.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Allauth emails coming from localhost instead of sendgrid account
I have set up django-allauth and everything is working but the emails generated, for example from reset password, come from localhost instead of the sender I want. Our emails use sendgrid and send with the right sender when using the django.core.mail send_mail command in a tests emails Is there a setting I am missing? These are the ones I have (along with a sendgrid password): EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = '******' # This works in test emails EMAIL_PORT = 587 EMAIL_USE_TLS = True ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 10 ACCOUNT_SIGNUP_FORM_CLASS = '******.views.SignupForm' ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'none' Thank you! -
url and django. ' not being escaped in url. django url param gets cut off
so two things. I have a url param that takes a name as a paramater in this case: Gino's%20East%20-%20Gold%20Coast notice how the spaces are being escaped, but the ' is not. the escape for ' is %27 this is breaking my django code. The ' is acting as a string delimiter so Gino's East - Gold Coast becomes Gino and then I get a 404 because I have no venue named Gino I am trying to solve the early delimit issue so when there is a ' in a param it persists and also does not cut off the string. How would one do this? -
How can I scape a double qoutes inside a django tag?
I would like to escape the these quotes "d-m-Y" in the code below. How can I escape these quotes, they make my project crash. <td><a href="{% url 'tender_list' date='{{ tenderEnquiries.d_assigned|date:"d-m-Y" }}' %}">{{ tenderEnquiries.c }} tenders</a></td> Thanking you in advance. -
Getting the ID of Related Objects in Django (not using the classic model id)
Let's say I have these modeles: class Profile(models.Model): ID = models.IntegerField(unique=True, primary_key=True) sfid = models.CharField(max_length=200) gender = models.CharField(max_length=5) organization_region = models.CharField(max_length=100) organization_country = models.CharField(max_length=100) organization_city = models.CharField(max_length=100) class Community(models.Model): ID = models.IntegerField(unique=True, primary_key=True) primary_community = models.CharField(max_length=100) def __str__(self): return "Community: {}-".format(self.primary_community) class ProfileCommunity(models.Model): profile_ID = models.ForeignKey(Profile,to_field="ID",db_column="profile_ID", on_delete=models.CASCADE,) community_ID = models.ForeignKey(Community,to_field="ID",db_column="community_ID", on_delete=models.CASCADE,) def __str__(self): return "ProfileCommunity: {}-{}".format(self.profile_ID, self.community_ID) What I need to do is get a Community from the Community model.e.g I tried this to retrive the list of "Community1": Profile.objects.filter(profilecommunity__community__in="Community1") But I am having this instead: django.core.exceptions.FieldError: Related Field got invalid lookup: primary_community How can I do it ? -
Reusable views method for multiple model classes Django
Guys I want to create a tools inventory app. I have this method that will do the exact same thing on all tools types! what I want to know is how can I use this method dynamically selecting what models to use(how to pass a model class as an argument). It's currently working only for one type of tool. My Models has an abstract class that has all common fields for all tools and various classes that inherit this class for tool specific fields e.i.(End mills, Drill-bits, pliers, screwdrivers all inherit common filed from my abstract class ) # Actualiza el valor cantidad existente # http://<domain.com>/nuevos-articulos/herramientas-de-corte/categoria-cortadores/<id-cortador>/incrementa/ def calcular_nueva_cantidad(ce, up, get_link): if get_link == 'inc-cortadores': total = ce + up else: total = -(ce - up) return total def calcular_nuevo_total(nce, pu): total = nce * pu return total # crea el formulario para la actualizacion de cantidad existente class updateForm(forms.Form): update = forms.IntegerField() def actualizar_cantidad(request, pk ): # trae de la base de datos el valor de la cantidad_existente cantidad_existente = Cortadores.objects.filter(pk=pk).values('cantidad_existente') c = cantidad_existente.values_list('cantidad_existente', flat=True) ce= c[0] # trae de la base de datos el valor de la precio_unitario precio_unitario = Cortadores.objects.filter(pk=pk).values('precio_unitario') p = precio_unitario.values_list('precio_unitario', flat=True) pu =p[0] # trae … -
Datatable toggle in django app doesn't work on Chrome OSX
I have a datatable like which currently shows only the shipped items: When I click on header 2, I want the table to show all the items like: I dynamically assign the class "non-shipped collapse" to a using django 'if' template tag. For Header 2, I have the code as follows: <th> <a data-target=".non-shipped" data-toggle="collapse"> Header 2</a> </th> This works perfectly fine on Windows 10 Chrome. However, in Chrome OSX, the highlighted row on clicking "Header 2" immediately appears and disappears. I have the latest version of Chrome on OSX. -
django - saving imagefile from form to s3
Everything in my form is saving except the image. The image isn't being uploaded to my s3 bucket either. Image does save and upload when i save the form through the admin. models.py class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') slug = models.SlugField(blank=True,unique=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True, related_name='local') image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) bio = models.TextField(null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return str(self.user.username) forms.py class ProfileEditForm(ModelForm): img = forms.ImageField(required=False) bio = forms.CharField(required=False) class Meta: model = Profile fields = ('img', 'bio') views.py @login_required def profileEdit(request): title = "Update Profile" profile, created = Profile.objects.get_or_create(user=request.user) if request.method == 'POST': form = ProfileEditForm(request.POST, request.FILES or None, instance=profile) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect("profile") elif request.method == 'GET': form = ProfileEditForm() context = { "form": form, "title": title } return render(request, "account/profile_edit.html", context) -
how can i add role based permission for each models that were created from inspectdb
I created models using (python manage.py inspectdb)then i ran python manage.py inspectdb > models.py this command as mentioned in documents after that i ran python manage.py migrate.Still i can't see the default add, delete ,change role based permissions when i created user and try to give access on Available user permissions for created models. My question is because i created models from inspectdb thats why permissions were not added in database if this this the case then how can i add the permission for each model to see the models will Available in user permissions section while creating user. -
Google Calendar API 403 error
I want to use Google Calendar API in my Django web app. I successfully got the access token using python social auth. Using that token, I tried calling list calendar API with python requests. Below is my code: import requests token = ... endpoint = "https://content.googleapis.com/calendar/v3/users/me/calendarList" headers = { "Authorization":"Bearer " + token, } requests.get(endpoint,headers=headers).json() However, I got the following response: u'error': u'code': 403, u'message': u'Insufficient Permission', u'errors': u'domain': u'global', u'message': u'Insufficient Permission', u'reason': u'insufficientPermissions' How can this be solved? I really want to solve this problem without using any other libraries including API Client Library. -
Bypass Django admin login by using another authentication method
Is there a way, when hitting Django admin site, it redirects to a 3rd party authentication page. User logs in there, then gets redirected back to Admin site without having to log in again? Basically I want to replace Django admin login by another authentication, so I can insert a link to my web app and admins can access admin page right away. -
How to disable checkbox after change in another field in django template?
I'm junior backend python dev (Django) but I have to do "easy" frontend task. I think it is easy but not for me because my frontend ends on F :( I'm using bootstrap in this app. I have a form field with some fields, two of them are checkbox named 'checkbox_1' and number field for price named 'price_1'. Checkbox on True means "Product is free" so... If checkbox_1 is True, field of 'price_1' should go disabled so I can't write on it. If 'price_1' is 0 and 'checkbox_1' is False, than it shows a message "Price can't be 0 if product is not free". I have tried with django templates using if statement like this: <form action="index.html" method="POST"> <div class="form-group"> <label class="control-label">{{ form.price.label }} </label> {{ form.price }} EUR </div> <div class="checkbox m-b-14"> <label>{{ form.free_product }} <i>/</i> {{ form.free_product.label }}</label> <!--AND HERE IS MY TRY--> {% if form.price.value == 0 %} TEST Price 0 {% else %} TEST price is bigger than 0 {% endif %} </div> </form> It works only after first enter the page. I think I have to use JS? Or maybe there is possibility to do it in bootstrap or django templates? Even if my example … -
What are the steps to update django app deployed with docker-compose since now django seems running old versions of code
I have django web application based on cookiecutter-django. The stack is build on several containers running: django, redis, celerybeat, celery worker, celery flower, postgres, caddy. When I launched application in production-like environment on VPS I have experienced strange behavior - django seems running old version of code (e.g. using version of form) despite checking out new code from git repository. I have tried few actions to "force" refresh of application code: docker-compose down and then, rebuild all containers with docker-compose build, and then docker-compose up similar rebuild as above but only for the container with django. When I inspect code inside django container - there is proper version of code. I did checkup app with Django Debug Toolbar - and seems that pages are are not loaded from cache (there are no calls to cache from backend, and there is number of queries to database which might indicate that pages are not loaded from cache). I was expecting that django will automatically detect change of code and restart running new code, additionally interpreter restart could be needed (which should be solved via putting containers down and rebuid). Are there ideas what else to check or try? Removing all containers, images … -
How to integrate django app with tcp server
Is there a way to connect django and a tcp server built with asyncio? I have a TCP server that should maintain long-lasting connections with clients, but I want to integrate it with Django so that a user can send data over the TCP server based on forms from Django I've heard of celery, but I do not know if it would be suitable for this application My current idea is to put a temporary tcp client to send data to the tcp server in the django code that receives posts. I would prefer not to do this because I would have to add more special cases to the TCP server in order to recognize that data is being sent from Django and not one of it's other clients -
How do I call a Child class method from within a Parent class Method in Django?
I am trying to acces a field of child from another model related by OneToOneField. class Parent(models.Model): ....... def get_child_name(self): return self.child_set // I tried this but didn't work for me class Child(models.Model): parent=models.OneToOneField(Parent) name=models.CharField(max_length=20) ....... I want to access name of child in a function of Parent model. -
django_auth_ldap vs postgres db using django models
I am creating an app where I store the USERS in a Postgres database with the help of the standard User Model, in my Django app i use Django queries to get all needed information, like "first_name", "username" .. etc i implemented Django_auth_ldap to start storing user identification data in an Openldap server if i want. But now, i'm confused to how to get the data i used to get using django queries. i don't want to change the behavior in my views, i want to continue using Django queries -
django 1.7 non existent parent node error
After squashing migrations and manually copying over functions from a run python method and changing all outside dependencies to the squashed migration file I'm getting this error where all the outside dependencies are saying the squashed file is nonexistent "Migration %s dependencies reference nonexistent parent node %r" % (migration, parent) -
AWS; cannot set up db, Error loading psycopg2 module: No module named 'psycopg2'
I'm new to AWS and I'm in trouble so much. I'm trying to set up db for my Django project. I cannot even connect to RDS in AWS so I ended up using elephantsql. But this error happens when I do eb deploy, django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' I already see there are some other people who had the same trouble but I'm sure I already installed the module on virtual environment using pip and I updated everything on git. But this error is still happening. settings.py is like this (it just looks like normal, though...) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME', ''), 'USER': os.environ.get('DB_USERNAME', ''), 'PASSWORD': os.environ.get('DB_PASSWORD', ''), 'HOST': os.environ.get('DB_HOSTNAME', ''), 'PORT': os.environ.get('DB_PORT', ''), } } psycopg2==2.7.5 btw. Anyone who can know how to fix this error? or Anyone who can give me clue? -
How to solve IndexError in Django 1.8.6
I am getting list index out of range error in my application. It is an e-learning system and the error occurs when I a student enroll tries to enroll in for a course. I am using django 1.8.6. This is my error. IndexError at /students/course/12/ list index out of range Request Method: GET Request URL: http://127.0.0.1:8000/students/course/12/ Django Version: 1.8.6 Exception Type: IndexError Exception Value: list index out of range Exception Location: D:\DjangoSchoolProject\env\educa\lib\site- packages\django\db\models\query.py in __getitem__, line 201 Python Executable: D:\DjangoSchoolProject\env\educa\Scripts\python.exe Python Version: 3.6.5 Python Path: ['D:\\DjangoSchoolProject\\educa', 'D:\\DjangoSchoolProject\\env\\educa\\Scripts\\python36.zip', 'D:\\DjangoSchoolProject\\env\\educa\\DLLs', 'D:\\DjangoSchoolProject\\env\\educa\\lib', 'D:\\DjangoSchoolProject\\env\\educa\\Scripts', 'c:\\users\\greendelta\\appdata\\local\\programs\\python\\python36- 32\\Lib', 'c:\\users\\greendelta\\appdata\\local\\programs\\python\\python36- 32\\DLLs', 'D:\\DjangoSchoolProject\\env\\educa', 'D:\\DjangoSchoolProject\\env\\educa\\lib\\site-packages'] and this is the python file I am using to enroll student. from django import forms from courses.models import Course class CourseEnrollForm(forms.Form): course = forms.ModelChoiceField(queryset=Course.objects.all(), widget=forms.HiddenInput) Any help will be greatly appreciated -
psycopg2.ProgrammingError: column "..." does not exist - through makemigrations error?
I pushed a project onto heroku and can't seem to win with the makemigrations on it. So first I thought everything went fine. After pushing it, I did the migrations and createsuperuser. All looked good and admin worked except for one section: accounts_userprofileinfo . Once I try to click on that table in admin this error shows up: Internal Server Error: /admin/accounts/userprofileinfo/ Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: column accounts_userprofileinfo.daca does not exist LINE 1: SELECT "accounts_userprofileinfo"."id", "accounts_userprofil... Usually you wouldn't do makemigrations on a live-server but I thought it might fix it so I did. Surprisingly it had an outcome: Migrations for 'auth': .heroku/python/lib/python3.6/site-packages/django/contrib/auth/migrations/0009_auto_20180709_2242.py - Alter field email on user Locally my makemigrations are with outcome: no changes, but there everythings works anyway. Funny thing is with the heroku postgres that no matter how often I do the makemigrations, the same thing keeps popping up with migrations for auth, like it doesn't save it. Not sure if thats causing the server error with my account_userprofileinfo but it might. Account Model: User._meta.get_field('email').__dict__['_unique'] = True class UserProfileInfo(models.Model): TYPE_CHOICES = ( ('yes', 'yes'), ('no', 'no'), ) POSITION_CHOICES = ( ('President', 'President'), ('Vize-President', 'Vize-President'), … -
Group permission connected to model list
My model: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) POSITIONS = ( ("volunteer", "volunteer"), ("employee", "employee"), ("manager", "manager"), ("director", "director"), ("vet", "vet") ) position = models.CharField(choices=POSITIONS, max_length=15) picture = models.ImageField(blank=True, null=True) And I am using class based views. I want to make a permissions to access diffrent views depending to 'position' value. I have found dozen of solutions and now I am a bit confused. What is the best way to make what I want to do?