Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trigger Django Signal from Different Database other than default db
I have different database other than default. @receiver(post_save, sender=Customer) def customer_post_save_task(sender, instance, created, **kwargs): print("hmm", created) But This only triggers when Customer is created from default db If Customer is created from another db it does not get invoked. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mydb': { 'ENGINE': 'django.contrib.gis.db.backends.mysql', 'NAME': 'Halanx', 'USER': 'root', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '3306', } When customer is created in mydb signal doesnot trigger. What can I do? -
How to capture middleware exception from other middleware in Django
I coding backend system with Django now, and I want control all exception from Django, so I create one middleware which name is CustomExceptoinMiddleware to control exception. But sometimes other middleware also raise exception, I hope CustomExceptoinMiddleware can capture it too, but I don't know how to do it. Can somebody help me? Thanks in advance! Python version: 3.7 Django version: 2.2.3 Setting.py MIDDLEWARE = [ ... "api.core.middleware.CustomExceptoinMiddleware ", "api.core.middleware.RaiseExcceptionMiddleware", ... ] # middleware.py class CustomExceptoinMiddleware(MiddlewareMixin): def process_exception(self, request, exception): print(f"Capture exception: {type(exception)}") class RaiseExcceptionMiddleware(MiddlewareMixin): def process_request(self, request): raise KeyError() -
Which is good for static and media when building a web server that can download files?
I want to build a web server that can only be downloaded to users by uploading large files. Where should I store my data files, static or media? Is it going to be good? (Size is 1 to 10GB compressed file.) Let me know if you have a better solution. -
Execute code in background after render page in Django
I have a script with twilio: from twilio.rest import Client def wa(testo): client = Client() # this is the Twilio sandbox testing number from_whatsapp_number='whatsapp:+14155238886' to_whatsapp_number='whatsapp:+39xxxxxxxxxx' ts = 'Anomalia Rapportino ' + str(testo) client.messages.create(body=ts, from_=from_whatsapp_number, to=to_whatsapp_number) I imported this script in view and I have this def: def grazieeprint(request, pk): intermedio = get_object_or_404(IntermProd, pk=pk) datilavoro = WhoWork.objects.get(pk=intermedio.work_id) try: return render(request, 'FBIsystem/thanksandprint.html', {'pkpreso': pk}) finally: try: appo = datilavoro.pezziorastima * 2 if datilavoro.pezziora >= appo: testo = datilavoro.pk subprocess.Popen([wa(testo)], shell=True) except: pass I need to run 'wa(testo)' after django load the page because all the process of sending message take approx 15/20 sec. I try whit 'try and finally' and whit 'subbrocess.Popen' but it send always the message before render the page. Please help TY -
ValueError: operands could not be broadcast together with shapes (256,) (128,)
I am making a Django Application using OpenCV and Dlib Library. I just wanted to implement face recognition feature using FILE UPLOAD. To store Image Hash at the backend I am using MongoDB. And hence I am using Djongo library to implement the same. Now here's the model which adds faces and it's hash to the database. Models.py class FaceDetails(models.Model): """ Model To Submit Face Details onto DB """ id_of_the_person = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4, editable=False) name_of_the_person = models.CharField(max_length=255, blank=True) img_hash = models.CharField(max_length=4000, blank=True, null=True, editable=True) remarks = models.TextField(help_text='Remarks', blank=True, null=True) image_of_the_person = models.ImageField(upload_to='uploads/') created_at = models.DateTimeField(auto_now=True) def __str__(self): return "{}".format(self.name_of_the_person) @property def get_absolute_image_url(self): return '%s' % (self.image_of_the_person) @receiver(signals.post_save, sender=FaceAddition, dispatch_uid="update_img_hash") def face_addition_completed(sender, instance, **kwargs): img = cv2.imread(instance.get_absolute_image_url) bbs = dlib_detector(img) for k, bb in enumerate(bbs): shape = sp(img, bb) curr_rep = list(facerec.compute_face_descriptor(img, shape)) if kwargs.get('created', True): fa_object = FaceAddition.objects.get(id_of_the_person=instance.id_of_the_person) fa_object.img_hash = curr_rep fa_object.save() Here's my views.py file which handles image upload against which we search the database. I have done it very crudely though. Views.py def comparison_with_db(curr_rep): id_list = [] img_h_array = [] distance = 0.0 qs_fa = FaceDetails.objects.all() for obj in qs_fa: to_str_rp = obj.img_hash.replace( '[', '').replace(']', '').replace(",", "").replace("'", "").split() # So that it can be converted to list … -
How to pass a list instead of dictionary in python-django to html page
I want to display the list "response_body" to my html page "home.html" For that I retrieved id attribute from response_body and the last id which was stored in "id" variable is printed to my html file. I want to retrieve all the id's and print it to the html page I know this will be done through loop but how? I am new to django and python any help will be greatly appreciated. I have tried printing the last id before the loop ended and I was successful with it but now I want to print all the id'd in the loop. i tried passing response_body to html instead of context but it gives me an error as response_body is a list type and it asked me to pass a dictionary variable like context which works fine. how can I print all the id's in the reponse_body list home.html <p>results</p> <p>{{id}}</p> views.py as this is a fairly long code i am posting just the code which maybe useful. response_body = json.loads(response.read().decode('utf-8')) for j in response_body: print(j['id']) id = j['id'] context = { 'id': id, } return render(request, 'home.html', context) -
How to add a reset password button in django-administration
How to add a reset password button in django-administration. And also Reset password button act like Email verificationI want like this image -
Adding XSS to OPTIONS Call in Django
I wanted to add x-xss-protection to all my requests in my Django application. So I added secure_browser_xss_filter = True. All my requests are now safe. But when I look at the options, I am still not able to see "x-xss-protection: 1; mode=block" How can I add X-Xss to my OPTIONS call also? -
Django 2.3: Struggling to have form send email with an attachment. Not sure how files should be treated/ handled using FormView
OK so I am attempting to create a form on my website that will take input from a user. The fields include first_name, last_name, email, and then a file upload form that should take their resume. Unfortunately I cannot get this program to send an email that includes any document I attach. I am using FormView with django in order to handle the incoming information which seemed straightforward until it came time to handle a file. What i've seen from various other answers is that you'd use something like request.FILES['resume'] but that seems to be if you aren't using formview. I've been struggling with this for over 10 hours and would really love to have someone point me in the right direction. forms.py: from django.core.mail import EmailMessage from templated_email import get_templated_mail from django.conf import settings class UploadResumeForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'First Name', }), required=True) last_name = forms.CharField( widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'Last Name', }), required=True) email = forms.EmailField(widget=forms.TextInput( attrs={ 'type':'text', 'class': 'form-control', 'placeholder': 'Email', }), required=True) resume = forms.FileField(widget=forms.FileInput( attrs={ 'name': 'resume', 'placeholder': 'Resume', 'class':'file-path validate', }), required=False) class Meta: title = 'Resume Upload' def send_message(self, email, first_name, last_name, file): email_obj = … -
How do I import a PostgreSQL table into d3 for use?
I am currently using d3.csv to import a table for use in a graph, however, I instead want to use a table from my Postgres database. I have the database connected to Django however I am unsure what d3 function I can use to fetch a table from the database and use it instead of a csv file. d3.csv("[link]", function(data) { console.log(data); Console.log(data) returns a table that looks like this: IMG -
Avoid dyanmic content's translation in msgstr
I am using Django translations for ja and de using makemessage. There is a translation in that I don't want to translate dynamic content in de. I am using the following translations. msgid " and %(level3)s subgroups" msgstr "und aller Untergruppen von %(level3)s " But now I don't want to use dynamic content 'level3' in msgstr. I simply need need und aller Untergruppen von. so I changed it to msgid " and %(level3)s subgroups" msgstr "und aller Untergruppen von " but while doing compilemessages it's getting error CommandError: Execution of msgfmt failed: /Users/treeni/treeni_produts/sustain-online/so-web/locale/de/LC_MESSAGES/django.po:4409: a format specification for argument 'level3' doesn't exist in 'msgstr' msgfmt: found 1 fatal error -
Django API: Connect to different databases dynamically
I have a django app which asks user for the ip address, port, username, password and database of the server it wants to connect to. I want to create an API that connects to these databases dynamically, and execute a query like SHOW TABLES on it. I am unable to figure out how to do this. What I think is I will have to dynamically set settings. py and use it. Also the databases can be of any type amongst SQL, Mongo. The user also specifies the type of database. -
Get daily number of call API
I have django rest framwork support android, ios, web with some version different api and different version mobile app. Now i hope know how many time each api call in 1 day, 1 month....for optimize and remove unused api. My question is: how to know each api call how many time in 1 day? Have any library support it or any way do it. Thank you! -
Django query implementation of Wilson Score algorithm
I'm trying to determine the best way to implement the Wilson Score algorithm in a Django project. The project is a mashup of typical forum features and reddit's upvotes/downvotes/trending page. Each forum has threads, and users can upvote/downvote a thread. Should I score and sort my threads in a database query, and if so, how would I do that using Django's DB models? My current solution is to fetch the forum's threads, and then sort in python. wilson_score.py from datetime import datetime from math import log epoch = datetime(1970, 1, 1) def epoch_seconds(date): td = date.replace(tzinfo=None) - epoch return td.days * 86400 + td.seconds + (float(td.microseconds) / 1000000) def score(ups, downs): return ups - downs def hot(ups, downs, date): s = score(ups, downs) order = log(max(abs(s), 1), 10) sign = 1 if s > 0 else -1 if s < 0 else 0 seconds = epoch_seconds(date) - 1134028003 return round(sign * order + seconds / 45000, 7) models.py from . import wilson_score class ForumThread(models.Model): category = models.ForeignKey(ForumCategory, on_delete=models.CASCADE) up_votes = models.IntegerField(default=0) down_votes = models.IntegerField(default=0) @staticmethod def get_trending_threads(category): return sorted(ForumThread.objects.filter(category=category), key=lambda x: wilson_score.hot(x.up_votes, x.down_votes, x.date_created), reverse=True) views.py threads = ForumThread.get_trending_threads(category)[offset:offset + 20] -
Convert this html template into Django
I am currently learning django, and at the moment I want to convert this page https://colorlib.com/etc/lf/Login_v6/index.html into django. I have tried heaps of times, still can't make everything right. Let me show you my work structure below. My problem is about using css and js under static/vendor fold. Seems the way I used got a bit problem, I have also attached my code for invoking the css and js under vendor. Thanks for any help. MyFirstDjangoWeb --project --setting.py --urls.py --wsgi.py --init.py --project_app --template --myHtml.html --migration --0001_initial.py --init.py --__init_.py --admin.py --apps.py --models.py --test.py --urls.py --views.py --static --css --images --js --vendor manage.py '''html ''' -
Adding functionality to a button in HTML
I am creating a web-page for an online supermarket using Python and Django framework and for each of those products is an "Add to Cart" option.I want to make the code such that when the button is clicked it increases the quantity of that product by 1. This is the code for the the whole product Card :- <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> -
NoReverseMatch pattern not found in django2
NoReverseMatch found for a url i have tried and {% url '/feedback/form/' %} i am using a feedback app. #feedback\urls.py from django.urls import path, include from .views import request_feedback urlpatterns = [ path('form/', request_feedback, name = 'get_feedback' ), ] #feedback\views.py def request_feedback(request): if request.method == 'POST': feedback_form = FeedBackForm(request.POST) if feedback_form.is_valid(): feedback_form.save() return redirect('') else: feedback_form = FeedBackForm() return render(request, 'feedback/feedbackform.html', {'feedback_form':feedback_form}) #webapp\urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('feedback/', include("feedback.urls")), path('user/',include("user.urls")), ] i am getting this error NoReverseMatch at /feedback/form/ Reverse for '' not found. '' is not a valid view function or pattern name i am using python 3.7 and django 2 i do mitigate this problem -
Can't fix "zipimport.ZipImportError: can't decompress data; zlib not available" when I type in "python3.6 get-pip.py"
I was trying to install Django. Turns out that course's teacher said that we will be working with Python 3.6 I install Python 3.6. Now it's my default, it somewhat replaced the last version I had; which is Python 3.5. Everything ok until that. But when I want to install Django doing "pip3 install django", it tells me that the module is already satisfied and therefore installed. I run "python3" command into my terminal. It runs Python 3.6. I try to import Django, and boom... "No module named 'django'". Then I realized pip3 was actually installing my modules into Python 3.5 and not 3.6. So what I do is to install pip in Python 3.6. I download get-pip.py and proceed to execute it with Python 3.6 typing in "python3.6 get-pip.py". Here is when the damn "zipimport.ZipImportError: can't decompress data; zlib not available" goes in. I've tried a ton of things and no one of them fixed the %^$! problem. I'm really tired. What I have already tried: python3.6 -m pip install django, which output is "/usr/local/bin/python3.6: No module named pip" apt install zlib, which output is "E: Unable to locate package zlib" apt install zlib1g-dev, which says that it's already … -
Passing model fields into functions as parameters to create other fields django
I following up with my question Creating new objects under specific parameters . I was trying to find out how to write functions into my django models to create default values on fields. I know how to do that, but now would like to take it a step further by adding parameters to the functions and using previous fields as the parameters. So far I have tried the following and each have given their own error messages when I try and migrate them. class NewTest(models.Model): score = models.IntegerField(default=0) def num(score): # Want the score parameter to be the score field new_num = score return new_num last_score = models.IntegerField(default=num(score)) Error: int() argument must be a string, a bytes-like object or a number, not 'IntegerField' class NewTest(models.Model): score = models.IntegerField(default=0) def num(self): new_num = self.score return new_num last_score = models.IntegerField(default=num(self)) NameError: name 'self' is not defined class NewTest(models.Model): score = models.IntegerField(default=0) def num(): new_num = self.score return new_num last_score = models.IntegerField(default=num) NameError: name 'self' is not defined Does anybody know how to do this, or know where there is documentation on this? -
[Django]The logged in person wants to download the file
I would like to provide the files in the django media url to the logged in users. However, in general media, if you know url, you can access without permission. What is the best way to solve it? The code below is 'views.py', which allows users to download files to the bulletin board. Please let me know if there is another solution. I also want to maintain good performance because it is a large file. views.py @login_required def index(request): files = os.listdir(settings.MEDIA_ROOT) # file full path # print(os.path.getsize(os.path.join(settings.MEDIA_ROOT, files[0]))) filelist = [(i, os.path.getsize(os.path.join(settings.MEDIA_ROOT ,i)), '/media/'+i) for i in files] print(filelist) return render(request, 'download/index.html',{'filelist' : filelist}) -
AttributeError at / 'tuple' object has no attribute 'get'
Estou iniciando meus estudos em Django e Python, no momento estou tentando criar um blog, mas quando tento executar a aplicação ocorre o erro: AttributeError at / 'tuple' object has no attribute 'get' AttributeError at / 'tuple' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.2 Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'get' Exception Location: /home/pedro/Documents/projects/django_pratice/myvenv/lib/python3.6/site-packages/django/middleware/clickjacking.py in process_response, line 26 Python Executable: /home/pedro/Documents/projects/django_pratice/myvenv/bin/python Python Version: 3.6.8 Python Path: ['/home/pedro/Documents/projects/django_pratice', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/pedro/Documents/projects/django_pratice/myvenv/lib/python3.6/site-packages'] Server time: Thu, 11 Jul 2019 21:35:35 -0300 Espero ver a pagina html -
How to set up multiple schema in django with oracle as a database?
My workplace is planning to use Python/Django as a backend framework and React on the front, on top of oracle db from ASP classic. Since our oracle db structured from the beginning of the company, we decided to keep it as is. From my understanding, schemas in oracle are typically accessed by username/password, thus need to have user/password for each schema to have an access and our oracle db has about 30ish schemas, containing numerous tables inside for each. Django, on the other hand, seems it only supports one schema at a time, based on app that is installed in settings.py, which sounds like the databases configuration need to have different user/password set up in settings.py for each app installed. So far, I've tried class Meta and DATABASES in settings.py; // class Meta class SomeModel(models.Model): ///some fields and data types... class Meta(): managed=False db_table=u'"schema\".\"table"' // DATABASES DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'multi_schema_db', 'USER': 'django_user', 'PASSWORD': 'secret', }, 'data': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'multi_schema_db', 'USER': 'data_user', 'PASSWORD': 'secret', }, } My questions is, is there any workaround to have an access into multiple schema where django has only one app installed? P.S. Correct me on any misunderstandings that … -
How to use Django + DJ Stripe to add user to group after they pay for a subscription
I have a Django web app using a custom user model based on AbstractUser. Users sign up and they can upload audio files which then fill an audio player. I want to have two tiers--free and paid. Free users can only upload 5 audio files. Paid users can upload unlimited. I will offer 3 subscription plans, Monthly, Semi-Annually (6 months), and Yearly. Currently there are two Groups in my django project. "Free User" and "Gold Member". In the upload view, there is a check that if a user has uploaded 5 files and they are a member of the "Free User" group, they are redirected to a page that says they must be a member. This page would have the three options I will mention below. . . I have created my plans in Stripe, and installed dj-stripe. I was thinking to have the process go like this: User signs up and they are automatically a member of "Free User" group. I have code to do this. After successful sign up, they would be redirected to a subscriptions page where they are presented the option to pick monthly, semi-annual, or yearly subscription. There would three columns with features/pricing and a … -
django unique object (not unique field)?
how to make a unique object (not unique per field) e.g: name : honda category : car success name : honda category : bike success name : honda category : bike failed coz all field have same value to another object if i use unique at the field, the second case will be failed, coz honda (name) already created my code : class Category(models.Model): name = models.CharField(max_length=127,unique=True) def __str__(self): return self.name class Brand(models.Model): name = models.CharField(max_length=127,unique=True) category = models.ForeignKey(Category,on_delete=models.CASCADE) def __str__(self): return self.name -
Customize error messages using django-rest-auth
I am using django-rest-auth for login and registration. If I try logging in using a wrong password, I get Request failed with status code 400. and the same message is shown if I signup trying to use a username that already exists. How would I get some more exact error messages to show in these different scenarios?