Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
sending notification through FCM token?
I login through an app which update the FCM token in my backend server. Now i have another end point which sends the notification which i am hitting through postman. What should be the authorization token in this case, would it be user access token or fcm token? -
How do I show only a subset of options in a Django dropdown menu
I have an app that allows users to signup and register for courses (from a 'TrainingInstance' model). These events have names etc and are categorised as Past or Current in the database (in the 'Training' model). When I show the BuildOrderForm in my template, I want only options for Current trainings to be shown in the dropdown menu. How can this be done in Django without javascript or Ajax? I have the following form in forms.py: class BuildOrderForm(forms.ModelForm): class Meta: model = Order fields = ['training_registered'] And the following models in models.py: class Training(models.Model): """ Model which specifies the training category (name) and whether they are Past or Present""" YEAR = ( ('current', 'current'), ('past', 'past'), ) name = models.CharField(max_length=200, null=True) year= models.CharField(max_length=200, null=True, choices=YEAR, default='current') def __str__(self): return self.name class TrainingInstance(models.Model): """ Creates a model of different instances of each training ( May 2021 etc) """ name = models.CharField(max_length=200, null=True, blank=True) venue = models.CharField(max_length=200, null=True, blank=True) training = models.ForeignKey(Training, on_delete= models.CASCADE, null = True) training_month = models.CharField(max_length=200, null=True, blank=True) participant_date = models.CharField(max_length=20, null=True, blank=True) staff_date = models.CharField(max_length=20, null=True, blank=True) graduation_date = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class Order(models.Model): REGSTATUS = ( ('registered', 'registered'), ('enrolled', 'enrolled'), ('holding', 'holding'), … -
Django - choosing between flairs dedicated to the server which user is posting on
I'm trying to make a reddit clone app which every server has its own set of flairs that the user can choose one of them while posting on that server. I've made a ServerFlairs model: class ServerFlairs(models.Model): server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='tags') name = models.CharField(max_length=20) primary_color = ColorField(default = '#ffff') secondary_color = ColorField(default = '#ffff') is_allowed = models.BooleanField(default=True) I've also added post_flair to the post model as a ForeignKey so users can choose between flairs dedicated to the server that they are posting on. but it shows all of the flairs that are available for all servers not just the ones that are available for the server which the user is posting on. Post Model: class Post(models.Model): ... server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='posts') creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='posts', null=True) created = models.DateTimeField(auto_now=True) type = models.CharField(max_length=5, choices=post_type_choices, default='text') votes_count = models.IntegerField(default=0) #this shows all of the flairs from all servers not just the one that user is posting on post_flair = models.ForeignKey(ServerFlairs, on_delete=models.CASCADE , default=1) so how can I change it so that post_flair only shows the flairs that are available for the server which the user is posting on? -
Post method not working, only get request
I have a form like this: <form method="post"> {% csrf_token %} <div class="mb-3"> <input type="hidden" class="form-control" id="url" name="delete-id" value="{{ url.id }}"> </div> <div class="mb-3"> <button type="submit" class="btn btn-primary mb-3">Delete</button> </div> </form> This form is embedded in a cell of a table. I make a post request in the form but when I'm testing the request.method, it always gives me the GET answer. if request.method == 'post': Url.objects.get(id=request.POST.get['delete-id']).delete() Here request.method is always GET and I don't understand why. -
Django treebeard count on each child
I'm using django-treebeard to create tree of Structures (some kind of folders). Each Structure could contain a Resource. When I list my Structures I need to know how many Resources are in current Structure and it's children. Is there a way to Sum them with aggregation? Example: - RootStructure - ChildStructure - Resource1 - Resource2 return Structure.get_root_nodes().annotate(resources_number=Count("resource")) resources_number = 0 (i want to get 2 because ChildStructure have 2 Resources) return parent_obj.get_children().annotate(resources_number=Count("resource")) resources_number = 2 when parent_obj is RootStructure Here are my models: class Structure(MP_Node): objects = StructureManager() name = models.CharField(max_length=100) description = models.CharField(max_length=500, blank=True, default="") class Meta(MP_Node.Meta): ordering = ("path",) class StructureResource(models.Model): resource_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) structure = models.ForeignKey( Structure, on_delete=models.CASCADE, related_name="resource" ) resource_id = models.IntegerField() resource_object = GenericForeignKey("resource_type", "resource_id") -
Docker - Media volume not storing data
I have a Django project in which I have a media volume that contains all the files that are uploaded. Some of those files are the objects of a Script model. However, there must be something in my definition/use of the volume as I get a No such file or directory: 'path_of_the_file' error when trying to access to my files. I tried different approaches, and discovered that when creating an object through the admin panel, the file was accessible until the container's next restart. I tried checking what was inside of my volume using this answer but I get a The specified path does not exist when trying to cd into the mountpoint. Here is the inspection result : C:\Users\stephane.bernardelli\Documents\TestApp\src>docker volume inspect testapp_media [ { "CreatedAt": "2022-07-21T14:34:17Z", "Driver": "local", "Labels": { "com.docker.compose.project": "testapp", "com.docker.compose.version": "2.6.1", "com.docker.compose.volume": "media" }, "Mountpoint": "/var/lib/docker/volumes/testapp_media/_data", "Name": "testapp_media", "Options": null, "Scope": "local" } ] And here is my docker-compose.yml: version: '3.8' services: rabbitmq3: image: rabbitmq:3-alpine ports: - 5672:5672 networks: - main postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=Scripts Application networks: - main ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: volumes: - static:/static - media:/media …