Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Cloud Video Intelligence checking free monthy usage programatically
I have been using Google Cloud Video Intelligence succesfully with my content with the following code for some time with my Django application running on Google App Engine Flex. gs_video_path ='gs://'+bucket_name+'/'+videodata.video.path+videodata.video.name video_client = videointelligence.VideoIntelligenceServiceClient() features = [videointelligence.enums.Feature.OBJECT_TRACKING] operation = video_client.annotate_video(gs_video_path, features=features) As explicitly stated by Google Cloud, each month the following is Feature First 1000 minutes Minutes 1000+ Label detection Free $0.10 / minute Shot detection Free $0.05 / minute, or free with Label detection Explicit content detection Free $0.10 / minute Speech transcription Free $0.048 / minute Object tracking Free $0.15 / minute Text detection Free $0.15 / minute Logo recognition Free $0.15 / minute Celebrity recognition Free $0.10 / minute How can I programatically detect that the free first 1000 minutes has been used, or the current usage for these features at that instant ? -
Open EDX lms login doesn't redirects to dashboard
Open EDX lms login doesn't redirects to dashboard, instead it goes back to homepage. Whenever I click the sign in button from any other page (like a course), it sign in perfectly, when I click the button from homepage, it returns to homepage and doesn't even show the logged in user. I think I have this code (main.html), that is sending the homepage url (or any other page when clicked from there). <%def name="login_query()">${ u"?next={next}".format( next=urlquote_plus(login_redirect_url if login_redirect_url else request.path) ) if (login_redirect_url or request) else "" }</%def> How can I make it perfect? -
How to translate form validation errors based on url?
I was creating a multi-linguistic app in Django,almost everything is done.I just have to translate the validation errors in another langauge if the user is on that. I wanna keep it simple.No external API'S and other stuff. Here's what i tried to do In my form I tried to get the current url. And then check what's the url and translate the errors based on that. def __init__(self, *args, **kwargs): current_url = kwargs.pop("url",None) print(current_url,"current_url") super(ContactForm,self).__init__(*args, **kwargs) fields = self.fields if current_url == "/nl/contact/": self.add_custom_error("name",{"max_length":"Je naam mag niet meer dan 20 tekens bevatten.", "required":"Voor het versturen van uw bericht hebben wij uw naam nodig, vul deze aub in!"}) self.add_custom_error("email",{"invalid":"Voer een geldig e-mailadres in", "required":"Voor het versturen van uw bericht hebben we uw e-mailadres nodig, vul deze aub in!"}) self.add_custom_error("subject",{"max_length":"Uw onderwerp mag niet meer dan 40 tekens bevatten.", "required":"Voer het onderwerp in om het bericht te verzenden!"}) self.add_custom_error("message",{"required":"Het berichtenblok moet worden ingevuld om een geldig bericht te kunnen verzenden!",}) elif current_url == "/en/contact/": self.add_custom_error("name",{"max_length":"Your name can't be more than 20 characters.", "required":"For sending your message we need your name.Please enter it!"}) self.add_custom_error("email",{"required":"For sending your message we need your email.Please enter it!","invalid":"Enter a valid email address!"}) self.add_custom_error("subject",{"max_length":"Your subject can't be more than 40 … -
how to iterate list in django html template
I have a list that i put in table in template in Django: <tr><th></th>{% for year in years %}<th>{{ year }}</th>{% endfor %}</tr> The years inlcude list or years from 2000-2020 whereas i wanted only print the last 5 years from the list so i tried: <tr><th></th>{% for year in years %}<th>{{ year[:4] }}</th>{% endfor %}</tr> however this way it does not work. How to iterate only 5 years from the list instead of 20. -
P5.js and Django: Saving a soundfile to a server
I am trying to record audio through the user's microphone and then save it as a wav on the server running Django. I based my code on this: https://discourse.processing.org/t/uploading-recorded-audio-to-web-server-node-js-express/4569/4 I am getting two errors: Error: [object ReadableStream] p5.js:78248 Fetch failed loading: POST "http://localhost:8000/ajax/postRecordedAudio/". The first thing my server code does is print out a message that "postRecordedAudio was reached", so I know it's getting to that url. I tried using a blobURL and passing that as a string. I tried using a form and attaching the soundblob to a file input field in the form. I tried making the soundblob into a file by adding a name and date attribute and then attaching it to the form. Any help is greatly appreciated! Here is the code, It just starts recording for one second and then tries to post it. <!DOCTYPE html> <html lang="en" dir="ltr"> <head> {% load static %} <script src="{% static '/js/p5.js'%}"></script> <script src="{% static '/js/addons/p5.sound.js'%}"></script> <script src="{% static '/js/addons/p5.dom.js'%}"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script> let soundFile; function setup() { mic = new p5.AudioIn(); mic.start(); soundRec = new p5.SoundRecorder(); soundRec.setInput(mic) soundFile = new p5.SoundFile(); button = createDiv(""); button.position(100,100); button.size(100,100); button.style('background-color', 'grey'); button.mouseClicked((mouseEvent)=>{ getAudioContext().resume(); console.log("recording...."); soundRec.record(soundFile); … -
Getting date value from django queryset
I have a Models like below class Member(models.Model): memberid = models.AutoField(primary_key=True, editable=False) memberdate = models.DateTimeField(default=timezone.now) fname = models.CharField(max_length=25) mname = models.CharField(max_length=25) lname = models.CharField(max_length=25) mobile1 = models.CharField(max_length=15) email = models.CharField(max_length=150) dob = models.DateTimeField(default=timezone.now) I am fetching data to display in the html template. For the view below is the code def updateMemberView(request, id): searchmem= id member = Member.objects.filter(memberid=searchmem).values() print(member[0]) return render(request, 'Member/member_update_form.html', {"member": member}) Now in print(member[0]) I am getting {'memberid': 13, 'memberdate': datetime.datetime(2020, 4, 11, 0, 0, tzinfo=<UTC>), 'fname': 'Akash', 'mname': 'chimanbhai', 'lname': 'khatri', 'mobile1': '', 'email': 'kashkhatri@yahoo.com', 'dob': datetime.datetime(2020, 4, 3, 0, 0, tzinfo=<UTC>)} But when I try to print the value of dob in template using member.0.dob it gives me error. Also when I try to execute command print(member[0].dob) this also give me error 'dict' object has no attribute 'dob' So How could I get the dob value in view and also in template. -
Django/Python Dynamic Microservices
I am trying to build a microservice architecture based on Python language and specially around Django and Flask. We were working on JHipster, which is based on SpringBoot and provides a set of library and "out-of-the-box" microservices. Now we moved to Python, we are looking for some packages, such as: A Gateway: an entrypoint with dynamic routing feature. A discovery server: allowing microservice to register and unregister (realtime) Of course, we can develop our stack but we think that it should already exists? -
Why does Requests' Session.get() raise an requests.exceptions.ConnectionError instead of requests.exceptions.Timeout, when a timeout occurs?
I'm sending a Requests GET request using a Session as follows: with requests.Session() as rs: with rs.get(url, params={}, headers={}, auth=self.auth, verify=self.ssl_verify, timeout=30) as r: ... I was expecting a requests.exceptions.Timeout error to be raised, when the timeout=30 had elapsed, but instead a requests.exceptions.ConnectionError was raised: Traceback (most recent call last): File "/Users/nlykkei/projects/atlassian-watchdog/confluence/confluence.py", line 118, in __producer with rs.get(url, params={}, headers={}, auth=self.auth, verify=self.ssl_verify, timeout=30) as r: File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/sessions.py", line 543, in get return self.request('GET', url, **kwargs) File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/sessions.py", line 530, in request resp = self.send(prep, **send_kwargs) File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/sessions.py", line 683, in send r.content File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/models.py", line 829, in content self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b'' File "/Users/nlykkei/projects/atlassian-watchdog/lib/python3.7/site-packages/requests/models.py", line 758, in generate raise ConnectionError(e) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='confluence.danskenet.net', port=443): Read timed out. The documentation clearly states that: If a request times out, a Timeout exception is raised. So, why is a requests.exceptions.ConnectionError raised in my case? -
Why I can't install pillow with pip
I created a ImageField in model.py file and when I tried to run Python gave me an error. It says I have to install pillow . So I typed pip install pillow command. Then it started installing and after some time (though I thought it was successfully installed) it gave another error and said that it was not successfully installed. It gave me bunch of red colored text that I didn't understand. -
How can I update sqlite3 after any time login in Django 2.2?
I use from django.contrib.auth.models import User in Django for Authentication. I want update 1 column of auth_user table when any user login. @login_required def showmap(request): return render(request,'index.html') -
Django pass a filtered query set between class based views
I have a Django class based ListView, which is filtered within its get_queryset function, using url parameters from a filter form, that returns an object_list. Now I want to export the filtered content of the ListView by using a button that calls a second class based view for exporting the list to a .csv file. Both views are not the problem, but how do I get the data from the ListView, after its filtered, to the export view. Tried something with sessions, but did not get that to work. Perhaps it is possible to hand over the filter parameters but I always ran into problems with the request.session cache, which seems not to be available, even if everything necessary is enabled in the settings. Any ideas for a good approach on this? Everything I read so far about sessions did not help especially with class based views. -
Django. Submitting form with valid data returns http 405 after submission with invalid data
trying to implement crud with ajax and got stuck with this error. When I fill the form with correct data it works perfectly fine, but if I try to submit the form with an invalid data to verify error handling and then re-submit it I get 405 error returned. The only thing what comes into my mind is problem with repeatable csrf_token verification, but I guess I'm incorrect... Here is my view for processing request: def create_employee(request): data = dict() if request.method == "POST": form = AddEmployee(request.POST) if form.is_valid(): form.save(commit=False) form.instance.works_for = request.user.works_for form.instance.property_id = request.user.property_id form.save() data.update({'form_is_valid': True}) employees = User.objects.filter(property_id=request.user.property_id) data.update({'html_single_employee': render_to_string('single_employee.html', {'object_list': employees})}) else: data.update({'form_is_valid': False}) else: form = AddEmployee() context = {'form': form} data.update({'html_partial_employee_create': render_to_string('partial_employee_create.html', context, request=request )}) return JsonResponse(data) Here is HTML with js: {% extends "base.html" %} {% block content %} <!-- Button that triggers modal with form to add an employee --> <div class="row mt-1 ml-3"> <button id="OpenCreateEmployeeModal" type="button" class="btn btn-dark btn-sm open-modal"> Add employee </button> </div> <!-- Modal itself --> <div class="modal fade" id="CreateEmployeeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> {% include "partial_employee_create.html" %} </div> </div> </div> <!-- Personell display section --> <div class="container"> <div class="row justify-content-center"> <table … -
Is it possible to change the management/commands directory in Django?
In Django it's possible to write custom management commands. These are stored by default in the proj/app/management/commands directory of your application. Is there a way to change this location to a custom directory? E.g. /proj/cmd/? For example, to change the migrations directory you can use the MIGRATIONS_MODULES setting. Is there an equivalent for management commands? It doesn't appear to be documented. -
Retrieve a python list from external python file(Django)
I'm trying to retrieve a python list that generates from an external python file(algorithm.py). In algorithm.py has a set of functions that used to generate a python list. There is no issue with algorithm.py file and it generates the python list as I expect. I followed the below steps to get the python list which generates in algorithm.py into views.py. 1.) Pass a variable(lec_name) from a function in views.py to algorithm.py and retrieve the output by using stdout as the below statement. lec_name = request.POST['selected_name'] result = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE) 2.) And then when I print(result.stdout), I receive the output(the python list which I expect) as an array of byte as below. b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]\r\n" 3.) Then I used print((result.stdout).strip()) to remove \r\n and It gives output as below. b"[['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']]" This gives the python list which I expect as an array of byte So what I need, retrieve the output(the python list which I expect) as a python list. How can I solve this? I tried lot of things, but none succeeded. I'm using Python 3.7.4, Django 3.0.1 -
Django + React. Set-Cookie does not set cookie (CORS enabled)
I have a React app, working with Django back-end. I have an authorization URL, I send axios.post() to the URL, and Django responses me back with a Set-Cookie header, but the cookie will not be set for some reason, even if I have CORS-policy configured like this: settings.py INSTALLED_APPS = [ 'MyApp.apps.MyAppConfig', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", # 3000 - React port "http://localhost:8000", # 8000 - API port "http://127.0.0.1:3000", "http://127.0.0.1:8000" ] Form sending code: const url_to_send = `${this.state.api_base_url}:${this.state.api_base_port}${this.state.api_user_url}/login/`; axios.post(url_to_send, `username=${this.state.username}&password=${this.state.password}`, {}, { withCredentials: true, }) Request headers: POST /api/v1.1/user/login/ HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Content-Length: 42 Accept: application/json, text/plain, */* Sec-Fetch-Dest: empty User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.162 Safari/537.36 DNT: 1 Content-Type: application/x-www-form-urlencoded Origin: http://localhost:3000 Sec-Fetch-Site: cross-site Sec-Fetch-Mode: cors Referer: http://localhost:3000/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US;q=0.9,en;q=0.8,bg;q=0.7,kk;q=0.6 Response headers: HTTP/1.1 200 OK Date: Sun, 19 Apr 2020 09:56:27 GMT Server: WSGIServer/0.2 CPython/3.6.9 Content-Type: application/json X-Frame-Options: DENY Vary: Cookie, Origin X-Content-Type-Options: nosniff Content-Length: 31 Access-Control-Allow-Origin: http://localhost:3000 Set-Cookie: csrftoken=dajeDwkCNv84lbhZ9xEqLCU5zr9BedlIgvgzrjFQJfcWTI9JYuf3jWtDpZwH9dn3; expires=Sun, 18 Apr 2021 09:56:25 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=9f50dovwlfia1ismtnlcr449dw55ljht; expires=Sun, 03 May 2020 09:56:25 GMT; HttpOnly; Max-Age=1209600; … -
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 30: 'else'. Did you forget to register or load this tag?
Error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 30: 'else'. Did you forget to register or load this tag? This is the display i do get -
Using the URLconf defined in products.urls, Django tried these URL patterns, in this order:
*from django.urls import path, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('products/',include('products.urls')), path('accounts/',include('accounts.urls')), ]* The above code of pyshop/url.py I could not login to admin page. -
Authorize client with a model other than User
In DRF, You can create custom authentication classes and schemes. But in the end, all of them should return a tuple of (user, auth). I have a special case where my endpoints are going to get called by multiple servers and each one of them has their unique secret, stored in the Server model and table in my app. How I can implement authentication of these servers while the entity being authorized is not a User, but some other model? This is my current code (not tested): from rest_framework import authentication from rest_framework import exceptions from .models import Server class ServerAuthentication(authentication.BaseAuthentication): def authenticate(self, request): server_name = request.META.get('X_Server') server_secret = request.META.get('Authorization') if not server_name or not server_secret: return None try: server = Server.objects.get(name=server_name, secret=server_secret) except Server.DoesNotExist: raise exceptions.AuthenticationFailed('No such server') return server, None -
JS function not working in Django template
{% extends 'home.html' %} {% load static %} {% block title %}Customer{% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form }} Date of Birth:(dd/mm/yyyy) <label> <select id="day"> <option value="1" onclick="day()">1</option> </select> </label> <label> <select id="month"> <option value="1" onclick="month()">1</option> </select> </label> <label> <select id="year"> <option value="1" onclick="year(">1</option> </select> </label> <button type="submit">Submit</button> </form> {% endblock %} JS file function day() { let dd = 1; for (dd = 1; dd <= 31; dd++) { document.getElementById("day") document.write("<option value=" + dd + ">" + dd + "</option>") } } function month() { let mm = 1; for (mm = 1; mm <= 12; mm++) { document.getElementById("month") document.write("<option value=" + mm + ">" + mm + "</option>") } } function year() { let yy = 1950; for (yy = 1950; yy <= 2020; yy++) { document.getElementById("year") document.write("<option value=" + mm + ">" + mm + "</option>") }} js function is not working i can't understand what happened i create separate file where i declare functions for date of birth form but it's not response any thing except the html -
Obtain DRF JWT token for users with no password set
I am building a Django Rest Framework backend and Angular frontend. I am using dj-rest-auth to authenticate the user with Discord. This all works fine. I want to use django-rest-framework-jwt to authenticate my calls from my frontend to my backend. You can use obtain_jwt_token from the package, but this requires a username and password. Since my users are logging in with Discord, I have user.set_unusable_password() in my UserManager. How can I obtain and refresh JWT tokens if the users have no password set? Also, how does one even access a user's password from their UserModel to pass it to the obtain_jwt_token URL? Thank you -
Django - Problems with Ajax Form
Hi I'm trying to develop an e-commerce website using Django. I want to use Ajax to handle the view of my checkout form after it has been submitted. After the form is submitted, I want it to go to : return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") , i.e http://127.0.0.1:8000/checkout/?address_added=True But for some reason, it is not going there. Rather it's being going to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=W4iXFaxwpdtbZLyVI0ov8Uw7KWOM8Ix5GcOQ4k3Ve65KPkJwPUKyBVcE1IjL3GHa&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on As a result, the form data is also not getting saved. I was thinking if it were because of the new version of Django. What I want to do is that after they submit the place order button, the form is going to be None, i.e disapper and then I would add a credit card form there for payment. But it is not happening. What is wrong here? Can anyone please help me out of this or is there a better way to do this? My forms.py: class UserAddressForm(forms.ModelForm): class Meta: model = UserAddress fields = ["address", "address", "address2", "state", "country", "zipcode", "phone", "billing"] My accounts.views.py: def add_user_address(request): try: next_page = request.GET.get("next") except: next_page = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if next_page is not None: return HttpResponseRedirect(reverse(str(next_page))+"?address_added=True") else: … -
Django 2.2.4 TypeError at /accounts/login __init__() takes 1 positional argument but 2 were given
TypeError at /accounts/login init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login Django Version: 2.2.4 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: E:\Python\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 blogsite/blogsite/urls.py from django.contrib import admin from django.urls import path,include from django.contrib.auth import views from django.contrib.auth.views import LoginView as auth_login from django.contrib.auth.views import LogoutView as auth_logout urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), path('accounts/login',auth_login,name='login'), path('accounts/logout',auth_logout,name='logout',kwargs={'next_page':'/'}) ] blogsite/blog/urls.py from django.urls import path,re_path from . import views urlpatterns = [ path('',views.PostListView.as_view(),name='post_list'), path('about/',views.AboutView.as_view(),name='about'), re_path(r'^post/(?P<id>\d+)$',views.PostDetailView.as_view(),name='post_detail'), path('post/new/',views.CreatePostView.as_view(),name='post_new'), re_path(r'^post/(?P<id>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'), re_path(r'^post/(?P<id>\d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'), path('drafts/',views.DraftListView.as_view(),name='post_draft_list'), re_path(r'^post/(?P<id>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'), re_path(r'^comment/(?P<id>\d+)/approve/$',views.comment_approve,name='comment_approve'), re_path(r'^comment/(?P<id>\d+)/remove/$',views.comment_remove,name='comment_remove'), re_path(r'^post/(?P<id>\d+)/publish/$',views.post_publish,name='post_publish'), ] -
Retrieve a python list from external python file
I have this script: lec_name = request.POST['selected_name'] out = run([sys.executable,'//Projects//altg//algorithm.py',lec_name], shell=False, stdout=PIPE) strVal = (out.stdout).strip().decode("utf-8") print(strVal) This script works fine and returns a python list from an external python file as a string(str). [['0', 'Subject01(IS0001)', 'Z Hall(65)', 'Thursday 10:00-12:00'], ['1', 'Subject02(IS42255)', 'N Hall(90)', 'Wednesday 08:00-10.00']] But I want that returned python list as a list, not as a str. I tried many similar solutions but nothing helped. How can I achieve this? Is there any better way to achieve what I need? I'm using Python 3.7.4, Django 3.0.1. -
Can I set multiple Static Roots in django?
My problem: I already have a static folder for .css .js and images. But I have another directory in my server that stores recorded video, which keeps populating on a daily basis. I want django to be able to access files from that directory, where the videos keep populating. What can be the solution to this? Is it possible to make multiple static roots? -
for engine in engines.all: TypeError: 'method' object is not iterable why? in django project
[ hello ,this code can not run with error for engine in engines.all: TypeError: 'method' object is not iterable ]1