Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to link 3 models / tables and filter by value in django
in my database I have three tables: account.customer with "id" field account_customer_groups with "group_id" field auth_group with "name" field how to link with object.filter these 3 models to select the "name" field of the auth_group table which has the value "myvalue" my accounts/models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError('Vous devez entrer une adresse email.') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email=email, password=password) user.is_staff = True user.is_admin = True user.save() return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=255, unique=True, blank=False ) nom = models.CharField(max_length=50, blank=False, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = "email" def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" return True def __str__(self): return self.email and my catalog/views.py from django.shortcuts import render from catalog.models import Book, Author, BookInstance, Genre from accounts.models import CustomUser from django.views.generic import ListView, DetailView from django.contrib.auth.models import Group class BookDetailView(DetailView): """Generic class-based detail view for a book.""" model = Book class AuthorListView(ListView): """Generic class-based list view for a list of … -
Media volume inaccessible to Celery using Docker
I'm dockerizing a Django app and I'm having quite some trouble with it. I have the Django app using postgres as well as nginx and gunicorn successfully settled. However, when dockerizing Celery, it seems that it doesn't have access to my media files. I've been looking for the reason for a few hours, but nothing came up. The only thing I saw that I found strange was that my media volume seems to be empty when checking on Docker desktop, but I don't even know if that's the way it should or not... I've tried different approaches on the definition of the media volume in my Celery container but to no avail. Here is my docker-compose.yml: version: '3.8' services: rabbitmq3: container_name: rabbitmq image: rabbitmq:3-alpine ports: - 5672:5672 postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=ThisPasswordShouldBeChanged19456 - POSTGRES_DB=Scripts Application ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: container_name: django_gunicorn volumes: - media:/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" depends_on: - postgres nginx: container_name: nginx build: ./nginx volumes: - .:/code - static:/static ports: - "80:80" … -
How do I pass variables from django to javascript?
{% for comment_tv in comment_tv_list %} {{ comment_tv.user }} {{ comment_tv.comment }} {{ comment_tv.stars }} {{ comment_tv.tv.id }} {% endfor %} <script> fetch("https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US") </script> I want to send comment_tv.tv.id in this code to javascript. I want to change tv_id to comment_tv.tv.id. How I do change the code? -
How to activate virtual environment while working on django project?
I have been through numerous similar questions and I still don't understand how are we activating virtual environment for Django projects. Please mention explanation for how each command works and one more questions is that why do we not need to install python in Django's virtual environment, I am getting confused. Thank you in advance, please help this newbie. -
Require behind the scenes for connecting database to django
When we create Django project using django-admin command we get settings.py. In that we have DATABASES part to be mentioned. we mention 'ENGINE' and 'NAME'. I want to know how does this info of engine and database name flow through various source files of python and where exactly is the code line where the django gets connected to database. I am using MongoDB database. I think it uses MongoClient('') code to connect, but where is it in source files? Thanks in advance -
How to use CSP_FRAME_SRC to To allow loading a page in an iframe of any site in Django?
I created a site in Django that I deployed on heroku. I am trying to display this site in an iframe contained in an html file on my hard drive. So I used Django-csp. I added the following line in my settings.py file: CSP_FRAME_SRC = ["localhost"] However when I load my html page, the iframe does not contain content and I get the error: gkwhelps.herokuapp.com refused connection. To solve the problem, I modified my settings.py file as follows: CSP_FRAME_SRC = ["*"] but I still get the same error. Being a beginner in Django-CSP, I don't really know how to get out of this situation. Thank you ! -
Get Data From Three Tables (JOIN)
1- In the CategoryManager table, we want to filter by the Manager field according to the request user (for example result = category_manager). 2- Using the category_manager list obtained from step 1, we want to list all courses belonging to these categories from the Course table. class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) class CategoryManager(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT, verbose_name=_('Course Category'), related_name="category_categorymanager") manager = models.ForeignKey(_user, verbose_name=_('Category Manager'), on_delete=models.CASCADE, related_name="user_categorymanager") class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200, verbose_name=_('Course Name')) ... price = models.DecimalField(max_digits=7, decimal_places=2, verbose_name=_('Course Price'), blank=True, null=True) slug = models.SlugField(unique=True, blank=True) category = models.ForeignKey(Category, related_name='courses_category', on_delete=models.PROTECT) -
get error class TestInformLogin has no attribute client
I wrote this code for testing views in django when I run it i get the following error response = self.clinet.get(self.inform_list_url) AttributeError: 'TestInformLogin' object has no attribute 'clinet' from django.test import TestCase,Client from django.urls import reverse from KnowledgeManagement.models import Members , TblInform class TestInformLogin(TestCase): def set_up_create_user(self): self.user = Members.objects.create(username='testuser',nationalCode = '1235' , mobileNumber = '094562', date_joined = '2021-11-22') self.user.set_password('12345') self.user.save() self.clinet = Client() self.clinet.login(username='testuser', password='12345') self.inform_list_url = reverse('inform_list') self.edit_inform_url = reverse('edit_inform', args= [1]) def test_inform_list_GET(self): response = self.clinet.get(self.inform_list_url) self.assertEquals(response.status_code,200) self.assertTemplateUsed(response , 'inform_list.html') def test_edit_inform_GET(self): response = self.clinet.get(self.edit_inform_url) self.assertEquals(response.status_code,200) self.assertTemplateUsed(response , 'inform.html') -
Problems with Geodjango and Gdal
Notes: Using Django 4.0.5, and Python 3.10 IDE: Pycharm Professional OSGEO4W version: 2 (https://download.osgeo.org/osgeo4w/v2/) Problem I cant get the gis library to work in Django. I followed the documentation: https://docs.djangoproject.com/en/4.0/ref/contrib/gis/install/#windows. Having followed these steps I get this error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal303", "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", "gdal201", "gdal20") I then looked into what version of GDAL, that OSGEO4W had installed and found it to be gdal305. So I went in on https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal, where I downloaded the wheel, for my version of python, (GDAL-3.3.3-cp310-cp310-win_amd64.whl) and used the command pip install GDAL-3.3.3-cp310-cp310-win_amd64.whl. I then changed the path variables to go for this version of gdal rather then the one installed with OSgeo4W. I then got the following error: OSError: [WinError 127] : The specified procedure could not be found After reading online, I found the following stackoverflow: OSError in Geodjango: [WinError 127] : The specified procedure could not be found However, did this not work for me, I still get the same errors (depending on where i set the gdal path). Other things i tried: I tried to use an earlier version of OSgeo4W, but the installer did not have any available download sites. I … -
Fetching a mobile or desktop template using django middleware
I have this code snippet that detects whther a request originates from mobile or from desktop https://stackoverflow.com/a/42280964/492293 import re def mobile(request): """Return True if the request comes from a mobile device.""" MOBILE_AGENT_RE=re.compile(r".*(iphone|mobile|androidtouch)",re.IGNORECASE) if MOBILE_AGENT_RE.match(request.META['HTTP_USER_AGENT']): return True else: return False def myfunction(request): ... if mobile(request): is_mobile = True else: is_mobile = False context = { ... , 'is_mobile': is_mobile, } return render(request, 'mytemplate.html', context) In my case i have two identically named template named services.html for instance in this view from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('services.html') return HttpResponse(template.render()) In my directories i have mobile/services.html and desktop/services.html I would like to show the mobile template if the request originates from a mobile device and another template if the request originates from a desktop computer. I have looked at this django middleware https://docs.djangoproject.com/en/4.0/topics/http/middleware/#process-view which runs before django calls the view. How can i add functionality to it to to tell django if to prefix mobile or desktop to loader.get_template('services.html') based on the detected request originator(web or desktop)? -
how do i update an image using django model form?
form = UploadDocumentsForm(instance=prev_visa) prev_visa contains image and file field when I use the form to update the model, the current image is not showing -
Django standalone app with data resource (GEOIP data)
I am using Django 3.2 I am writing a standalone app that uses geo-ip2 I have download MaxMind's GeoIP database, and I want to share that data with other projects that use my application (instead of having to create copies of the database, for each project using my standalone app. According to the GEOIP documentation, a GEOIP_PATH needs to be specified in the settings.py file of the project. My question is - how do I set the path to the directory of my installed app? A quick and dirty way would be: settings.py import myapp GEOIP_PATH = f"{myapp.__path__}/{KNOWN_PATH_TO_DATABASE} Is there a better way of referencing data exported by a standalone application? -
IntegrityError at /api/users/profile/update
I am trying to implement an update user functionality but whenever I try to update a user I get back an IntegrityError saying: UNIQUE constraint failed: auth_user.username Here's what I have so far: Those are my serializers for the user: class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin'] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def get_name(self, obj): name = obj.first_name if name == '': name = obj.email return name class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) Here's my view method: @api_view(['PUT']) @permission_classes([IsAuthenticated]) def updateUserProfile(request): user = request.user serializer = UserSerializerWithToken(user, many=False) data = request.data user.first_name = data['name'] user.username = data['email'] user.email = data['email'] if data['password'] != '': user.password = make_password(data['password']) user.save() return Response(serializer.data) And this is my user action: export const updateUserProfile = (user) => async (dispatch, getState) => { try { dispatch({ type: USER_UPDATE_PROFILE_REQUEST, }); const { userLogin: { userInfo }, } = getState(); const config = { headers: { "Content-type": "application/json", Authorization: `Bearer ${userInfo.access}`, }, }; const { … -
Why is staticfiles not able to find or serve .css, using FORCE_SCRIPT_NAME in docker
In development (DEBUG=True) mode, running in docker on a host where the site is served with a pre-pended path corresponding to a branch, I am unable to get static files working. Using python 4.0.6 In settings.py I have these settings: DEBUG = True BASE_DIR = Path(__file__).resolve().parent.parent # default generated FORCE_SCRIPT_NAME = "https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/" INSTALLED_APPS = [ ... 'django.contrib.staticfiles', STATIC_URL = 'static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) In my html file: {% load static %} <html> <head> ... <link rel="stylesheet" href="{% static 'tableau_explorer/style.css' %}"> And my css is in: django_root/tableau_explorer/static/tableau_explorer On my development machine, both running manage.py from the sheel, and in a dockerfile, it works. In that setting, I don't have FORCE_SCRIPT_NAME. When it is on the other docker host, the generated HTML <link rel="stylesheet" href="/static/tableau_explorer/style.css"> And I get a 404 error. If I change: STATIC_URL = 'https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/static/' Then it instead of a plain 404 I get message that it's getting HTML instead of css, because the server is returning this Request Method: GET Request URL: http://https://pmdocker01d.pm.local:8443/bi-web-utils/ta0624/static/tableau_explorer/style.css Using the URLconf defined in bi_web.urls, Django tried these URL patterns, in this order: admin/ .... The current path, static/tableau_explorer/style.css, didn’t match any of these. For the other docker host I tried adding … -
Is there a way to make a collapsed inline initially visible in Django admin, if it has a value?
I am programming a website builder in Django, and each page has lots of fields to fill out. Some of them are pretty arcane, and to keep from cluttering up the page they are initially hidden: class ScriptInlinePage(admin.TabularInline): model = Page.script.through extra = 0 fields = ('active', 'script', 'order', ) verbose_name = "script set" verbose_name_plural = "script sets" classes = ['collapse'] In the interests of streamlining the page, I have made it so that collapsed inlines are unobtrusive: Script Sets (Show ▶) However, these initially-hidden fields can have a disastrous effect if they contain a value and the user is unaware of it. I am looking for a way to either: add a class collapsed but initially visible if not empty, or modify the collapse class so that it is only initially collapsed if it's empty I have tried adding to models.py something like: def is_empty: if self.count > 0: return True else: return False but I don't know how to use this information in the Admin class to get the effect I want. Similar question: I thought I saw a way to make an inline collapsible without making it initially collapsed, but after much googling I can't find it. … -
What is the most efficient way to reload a div without refreshing the whole page in django?
I am looking for the most efficient way that I can present on a live web page data such as a table with data from the database, that when a new record is added to the database the table updates itself without the user having to refresh the page. I have tried the method with Django and Ajax but I don't find it efficient because it has to refresh at a certain time but I only want it to refresh when a new record is added to the database. What methods could you recommend? -
Which Authorization Grant to use for Django Oauth2 toolkit?
I am planning to deploy a separate resource server and an authorisation server, both running on django oauth toolkit. Assuming that the clients or the applications using our API services are in the same organization, and will host their frontend to use our APIs, and the users will be logged in on their side and we just have to authorize those clients (that are running the application). Which Grant Type Should I use? -
Can I render templates in APis for the front-end
Am actually new to programming and am trying out Django along the way I start hearing about APis(django-restframework) and its starting to confuse me cause am seeing code every where about Apis but never seen a front end. My question is can I build my backend end inform of an Api and still be able to render my templates for the frontend just like in normal djangoframework(get already built template then just fix in the project).At the point of user login tokens a provided how will I handle those tokens or the tokens are just for communication with other software and irrelevant to the user -
can not login in django by authenticationform
i am unable to authenticate any normal user in my website, when i do login in admin site, it allows me to do login, but whenever i do login as normal user it does not allow me to do login, Views.py Here is my views.py file,FORM I HAVE USED INBUILT FORM DJANGO AuthenticationForm() from django.shortcuts import redirect, render from .forms import jobglobeluserform from .models import jobglobeluser from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate,login,logout,views from django.contrib.auth.decorators import login_required def userlogin(request): if request.method == "POST": fm = AuthenticationForm(request=request, data=request.POST) if fm.is_valid(): username = fm.cleaned_data.get('username') password = fm.cleaned_data.get('password') user = authenticate(request,username=username, password=password) if user is not None: login(request, user) return redirect('/jobseekersprofile/') else: fm = AuthenticationForm() return render(request, 'jobglobel/userlogin.html', {'form': fm}) -
No module named django-filter
I am trying to use django-filter. But it errors with no module named django-filter. Thanks for help. INSTALLED_APPS = [ #, #, #, 'django-filter', ] django-filter 2.4.0 -
I have some proplemi with the visualization of images in the mail in django
I have some proplemi with the visualization of images in the mail in django, I show you the code below. The image link points correctly to the image but is not displayed when, the image is a logo in png so it should be fine. I do not understand where I am wrong or what is missing to show the image view from django.core.mail import send_mail from django.template.loader import render_to_string def contatti(request): if request.method == "POST": form = SupportForm(request.POST) if form.is_valid(): nome_completo = request.POST['nome'] + ' ' + request.POST['cognome'] oggetto = "Richiesta di supporto" mail = request.POST['email'] msg = request.POST['messaggio'] privacy = request.POST['privacy'] destinatario = ['riccardo.test67@gmail.com'] protocol = 'http' domain = '127.0.0.1:8000' # html data_email = { 'protocol': protocol, 'domain': domain, 'nome_completo': nome_completo, 'mail': mail, 'msg': msg } msg_html = render_to_string('email/support.html', data_email) # invio send_mail( oggetto, msg, mail, destinatario, html_message = msg_html ) else: form = SupportForm() context = {'form': form} return render(request, 'contatti.html', context) html {% load static %} <html lang="it"> <head> <title>Richiesta di supporto</title> <style> @font-face {font-family: Titolo; src: url('http://127.0.0.1:8000/static/font/titolo.ttf') format('truetype');} </style> </head> <body> <table style="width: 600px; border-spacing: unset; margin: 0 auto;"> <!-- head --> <thead> <tr> <td colspan="2" style="padding-bottom: 1rem;"> <img src="{{ protocol }}://{{ domain }}{% static … -
How to remove a plugin in Django CMS?
I have registered my plugin using the code @plugin_pool.register_plugin class FAQPlugin(CMSPluginBase): model = FAQ name = "FAQ" render_template = "plugins/faq.html" cache = False allow_children = True require_parent = False def render(self, context, instance, placeholder): context = super().render(context, instance, placeholder) return context However, when I decide to remove the plugin from code though it's not used on a page anymore, I have an error: KeyError at /en/product/ 'FAQPlugin' -
What steps would I have to take in making this specific type of website?
I need to make a web app where the user can upload specific type of pdf invoices, and the required fields are extracted and displayed on the website. I have made the python code for extracting the required data and the web page(using flask) for uploading the documents. The uploaded documents are currently being saved in a folder on my computer, from which the python code is extracting the data. I would like to know the necessary steps I would have to take to finish and deploy the website in the easiest and quickest manner possible, so that anyone in my office can use it and upload the specific type of pdf invoices to it. Here's the code for extracting details from the pdf invoices: import os import pytesseract import re import pdfplumber import pandas as pd po_re=re.compile(r"PO [#][:]\sTRN[_]\d{2}[-]\d{4}[_](\d{4}|\d{3}|\d{2}|\d{1})") shipto_re=re.compile(r"SHIP TO((?:.*\n){1,4})") specs_re=re.compile(r"TNOP(?:[A-Z]){4}(\d{4}).*") dub_re=re.compile(r"\d{2}[.]\d{1}") qty_re=re.compile(r"\d{1}?(?=\s\d{2}[.]\d{1}\s[%])") listoflist=[] files=[] directory=r"C:\Users\mihir\settls\PO\POs\fbpdfs" for filename in os.listdir(directory): if filename.endswith(".pdf"): files.append(filename) print(files) df=pd.DataFrame() header_list=["PO","ITEM","Qty","SHIPTO"] df = df.reindex(columns = header_list) for f in files: pdf = pdfplumber.open(r"C:\Users\mihir\settls\PO\POs\fbpdfs"+"\\"+f) specs=[] qty=[] shipto=[] #ship=[] for i in range(0,len(pdf.pages)-1): page = pdf.pages[i] text = page.extract_text() for line in text.split('\n'): if po_re.match(line): po=line for line in text.split('\n'): if specs_re.match(line): specs.append(line) shipto += shipto_re.findall(text) … -
TypeError: String indices must be intergers Django
I am trying to store a dictionary item but i receive this particular error and i can't seem to wrap my head around why my dictionnary looks like this comment = {'en': 'The SIDHistory attribute must be cleared', 'fr': "L'attribut SIDHistory doit être effacé"} and the function I use is if y.get('comment'): # print('Comment :') comments = y.get('comment') print(comments) print(comments["en"]) print(comments["fr"]) # print(' Comment in English :', comment['en']) field_comment_english = comments["en"] # print(' Comment in French :', comment['fr']) field_comment_french = comments["fr"] else: # print(' Comment in English : None') # print(' Comment in French : None') field_comment_english = 'None' field_comment_french = 'None' It prints the variable I want without problem but then I receive an error at the end of the compilation telling me File "/Users/cmahouve/PycharmProjects/secad/apps/rules_management/views.py", line 50, in all_rules_interpreter print(comments["en"]) TypeError: string indices must be integers -
import custom module to django settings with string path
I have a permissions.py file at my core app in django which I want to use its My_has_permission class for project level permissions in settings.py. note settings.py and permissions.py are in same folder. so I tried REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ '.permissions.My_has_permission', ] } but it gave this error: TypeError: the 'package' argument is required to perform a relative import for so how can I have this package as my DEFAULT_PERMISSION_CLASSES? here on Im explaining my tries: I want the opposite of what importlib.import_module('.a', package='b') does and also make another ss.py and with from .permissions import My_has_permission print(My_has_permission.__file__) tried to get the path but gave error: ImportError: attempted relative import with no known parent package, this error is not because djangorestframework is not installed. note I say this because I have used some imports from rest_framework. besides error is from from .permissions import My_has_permission in ss.py so my question is it my `` faulty? from rest_framework import permissions PERMS_MAP = { # 'OPTIONS': 'view_', 'HEAD': 'view_', 'GET': 'view_', 'DELETE': 'delete_', 'PATCH': 'change_', 'POST': 'add_', 'PUT': 'change_' } class My_has_permission(permissions.BasePermission): app_label = view.queryset.model._meta.app_label model_name = view.queryset.model._meta.model_name return request.user.has_perm(str(self.app_label+'.'+PERMS_MAP[request.method]+self.model_name)) or request.user.is_admin or request.user.is_superuser