Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to reduce validation code for list of uuid4
All query params will take list of alias. Tryig to do it in simple way.But It has repeat loop from app.helper import uuid4_validator oders =self.request.queryparams("orders", "") #list or string , this field no mendatory products =self.request.queryparams("orders", "") #list or string , this field no mendatory custom_filter = {} if orders: temp_list=[] for temp in orders: if uuid4_validator(temp): temp_list.append(temp) custom_filter["Order__alias__in"] = [temp_list] if products: temp_list=[] for temp in products: if uuid4_validator(temp): temp_list.append(temp) custom_filter["Product__alias__in"] = [temp_list] Stock.object.filter(**custom_filter).update(price=400) -
Multiple functions running in the background
There are 2 functions, a and b. It is necessary that both functions work in the background. The first function should work continuously in a circle, and the second will have to run periodically - with an interval of 5 minutes, for example. What is the best way to implement this? Celery? -
Getting validation error 'is_staff': ["'true' value must be either True or False."] while implementing SSO using djangosaml2
I tried to implement SSO for my Django project. when I tried to login form SP ('/sso/login') I got the correct response from my IDP but on SP side 'sso/acs' it throwing a validation error. {'is_superuser': ["'true' value must be either True or False."], 'is_staff': ["'true' value must be either True or False."]} When I removed is_staff and is_superuser from SAML_ATTRIBUTE_MAPPING. SSO is working. Project packages - django 1.11, postgress, djangosaml2idp 0.5.0, for IDP djangosaml2 0.17.2 for SP My setting for SP: SAML_USE_NAME_ID_AS_USERNAME = True SAML_DJANGO_USER_MAIN_ATTRIBUTE = 'email' SAML_DJANGO_USER_MAIN_ATTRIBUTE_LOOKUP = '__iexact' SAML_CREATE_UNKNOWN_USER = False SAML_LOGOUT_REQUEST_PREFERRED_BINDING = saml2.BINDING_HTTP_POST SAML_ATTRIBUTE_MAPPING = { # SAML : DJANGO # Must also be present in attribute-maps! 'email': ('email', ), 'username': ('username', ), 'account_id': ('account_id', ), 'is_staff': ('is_staff', ), 'is_superuser': ('is_superuser', ), } Error Traceback: Traceback (most recent call last): File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/views/decorators/http.py", line 40, in inner return func(request, *args, **kwargs) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/djangosaml2/views.py", line 316, in assertion_consumer_service create_unknown_user=create_unknown_user) File "/Users/patilliteshc/Virtual_Envs/spEnv/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 73, in authenticate user = backend.authenticate(request, **credentials) … -
Database queries to 'cache' are not allowed in this test in django 2.2
I'm migrating project to django 2.2 from django 1.11. We have database based cache that runs on different database (not on default). When running tests, we get the following error: AssertionError: Database queries to 'cache' are not allowed in this test. Add 'cache' to users.tests.UserLogTestCase.databases to ensure proper test isolation and silence this failure. Adding the 'cache' database to the databases variable of the TestCase solves the problem (or setting it to '__all__'), the problem is that this has to be done per test. Is there any other (more global) way to solve this? -
Is there any source where I can go to learn how to make a not realtime messaging system with django, maybe using modules
I want to start a messaging system in my website, and I have tried to make a messaging system with Channels but I have a problem with the WS and the WSS for the websocket and I don't really know how to fix it, so I was wondering if there are any other ways to do this. Thanks for any help -
Connecting to EC2 Django Server
1. I have opened port 8001 on inbound traffic on EC2 security group. 2. Ran python manage.py runserver 0.0.0.0:8001 Shows 'Starting development server at http://0.0.0.0:8001/' 3. Tried to access the public EC2 address (ipv4 public 60.x.x.1:8001 or Public DNS (IPv4) http://ec2-x.x.x.compute.amazonaws.com:8001) I also added the public address above to the settings.py I can't seem to get the page loading. What needs to be done here? I get either not accessible or This site can’t be reached. -
All allowed hosts in settings file not working on Django site on Windows machines
The main allowed host - www.mysite.com is working on all browsers/ios/android/etc. However, mysite.com is not working on all browsers. It's a Django site and I've added these two allowed hosts into the settings file. It's only working on Chrome and Safari. How do I fix this for Windows machines? -
Structuring my Axios POST request to send my Django Rest Framework Stripe form data
I am working with default Stripe code to generate a Token that proves the payment form was successfully submitted. I'll post the code below for clarity within this post. I'm able to see the token if I console.log(token), but my server (Django Rest Framework) is giving me a 500 error with django.utils.datastructures.MultiValueDictKeyError: 'stripeToken' . From my limited research, this is saying the request.POST doesn't see a key of stripeToken. Do you think this is an error on how my server is handling this, or could I have written some incorrect Javascript? Here is my VueJS code: mounted: function () { var that = this; var stripe = window.Stripe(process.env.STRIPE_PUBLISHABLE_KEY_TEST); var elements = stripe.elements(); var style = { base: { color: '#32325d', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; var card = elements.create('card', {style: style}); card.mount('#card-element'); card.addEventListener('change', function (event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); var form = document.getElementById('payment-form'); form.addEventListener('submit', function (event) { event.preventDefault(); stripe.createToken(card).then(function (result) { if (result.error) { var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { stripeTokenHandler(result.token); } }); … -
Django Convert F type to float on query
I have 2 model in django a zone and a shop, models are like this: from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.contrib.gis.measure import D from location_field.models.spatial import LocationField class Zone(models.Model): name = models.CharField(max_length=200) location_point = LocationField(based_fields=['city'], zoom=7, default=Point(51.67, 32.65)) radius = models.IntegerField(default=1000) # radius in meters class Shop(models.Model): name = models.CharField(max_length=200) location_point = LocationField(based_fields=['city'], zoom=7, default=Point(51.67, 32.65), null=True, blank=True) zone = models.ForeignKey(Zone, on_delete=models.CASCADE, null=True) LocationField is a PointField with better map in django admin. I want on every shop saving select zone automatically base on shop location , zone location and radius. If there is no zone with radius to support shop it will be None. I tried this query: zone_list = Zone.objects.filter(location_point__distance_lte=(shop.location_point, D(m=models.F('radius')))) But I get this error: TypeError: float() argument must be a string or a number, not 'F' How can I fix this? -
POSTMAN: Post method using raw body returns 500
I tried to POST a query in json in postman's raw body like below: and I got 500 internal error server and HTML results like below Otherwise, I'm able to POST using form-data and from a script ran from the terminal using the same json format. I use Django 1.5.12 to serve the API and python 2.7. Can anyone help? -
How to run Celery schedule only a number of times and quite until the task is called again?
I am using django + celery task scheduler to run a task scheduled for once every month. But I just want this task to run for a few number of months only, e.g 3 months or 6 months or 9 months.. How do I get to stop the worker from executing further task and then restarting whenever the task is called again? -
How to add permissions to edit own in django admin based on value in model?
I have a question about Django-Admin. Every item in my Django admin has got the "EngagementManager" field, which contains the name of the person. When you log in Django, your username is the same as the field, which I mentioned previously. I need to implement the feature that login user could change/edit only items when the field "EngagementManager" will match the login user. Can someone please provide me the piece of code and some little guide where to put it, please? -
Python-kenel error:PermissionError: [Errno 13] Permission denied:
I set a enviroment of tensorflow. I wanna to check whether it works well.So I open the Jupyter Notebook When I open Jupyter Notebook and establish a new file, it show kenel error. Traceback (most recent call last): File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\web.py", line 1699, in _execute result = await result File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\sessions\handlers.py", line 72, in post type=mtype)) File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 88, in create_session kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name) File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 742, in run yielded = self.gen.throw(*exc_info) # type: ignore File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 101, in start_kernel_for_session self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name) File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 735, in run value = future.result() File "D:\Anaconda3\envs\tensor36\lib\site-packages\tornado\gen.py", line 209, in wrapper yielded = next(result) File "D:\Anaconda3\envs\tensor36\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 168, in start_kernel super(MappingKernelManager, self).start_kernel(**kwargs) File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel km.start_kernel(**kwargs) File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\manager.py", line 240, in start_kernel self.write_connection_file() File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\connect.py", line 547, in write_connection_file kernel_name=self.kernel_name File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\connect.py", line 212, in write_connection_file with secure_write(fname) as f: File "D:\Anaconda3\envs\tensor36\lib\contextlib.py", line 81, in __enter__ return next(self.gen) File "D:\Anaconda3\envs\tensor36\lib\site-packages\jupyter_client\connect.py", line 102, … -
Django: expected string or bytes-like object while trying to set DateTimeObject
I have defined a Model Field as: SomeModel(models.Model) some_date = models.DateTimeField(default=timezone.now) Now when i am trying to save the model providing a date to some_date it gives error expected string or bytes-like object @ /django/utils/dateparse.py in parse_datetime, line 106 test_date = timezone.now() SomeModel(somedate = testdate) # SomeModel.save() it says expected string or bytes-like object where as test_date = datetime.datetime(2019, 11, 20, 20, 9, 26, 423063, tzinfo=pytz.timezone("America/New_York") SomeModel(somedate = testdate) SomeModel.save() works -
Django and Angular POST credentials were not provided
error when i try to login to my proyect, im using postman for test the login and send me error "detail": "Authentication credentials were not provided." my url.py urlpatterns = [ url(r'^api-login-user$', views.LoginUserView.as_view()), url(r'^', TemplateView.as_view(template_name='angular/index.html')), url(r'^', include(router.urls)), url(r'^auth/', ObtainAuthToken.as_view()), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] my view.py class LoginUserView(APIView): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user: payload = jwt_payload_handler(user) token = { 'token': jwt.encode(payload, SECRET_KEY), 'status': 'success' } return Response(token) else: return Response( {'error': 'Invalid credentials', 'status': 'failed'}, ) my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', } -
Is there a way to pass a variable "through" the allauth process?
I have a website that requires a account creation for two different kinds of users. Users will create an account by one path, and admins will create an account by another pass. I am using django-allauth for my authorization process. I am looking for a way to pass an "?admin=true" parameter through the process so that I can write it into the user record. Is there an easy way to do this, like a setting? I am still getting my feet wet with django. When I open the allauth code, I feel like it is on a different level. Do I just need to suck it up and pass a parameter from "accounts/signup" to the authorization email to the email authorization page? Or is there a way to pass supplemental infomation through? -
Django 2: where to add urlencode to correctly parse plus signs
I get a q variable as follows: q = self.request.GET.get('q') However if the value of the parameter value passed has a + sign this is lost. How/where do I encode the URL to convert, for example, + signs to %2B? -
How to modify the Login view in inherited class in django?
I want to handle "confirm form resubmission" pop ups, when the user refresh the login page with incorrect data. I'm using a class named: UserLogin inherited from LoginView('django built-in'), I know that I need to write a method in my own class to handle this issue, and I did it with HttpRespone for my Registration view. who can I solve it for my Login View? -
I can't connect MySQL version 8 to Django 2.2 project
I have tried pretty much everything, including scouring StackOverflow to solve this issue yet I still seem to be faced with the problem. I am trying to connect my Django 2.2.6 project to my MySQL version 8 database with zero luck. I have changed the settings.py file to contain the following key value pairs in the databases dictionary: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'portfoliodb', 'USER': 'c**********s', 'PASSWORD': 'XXX', 'HOST': 'localhost', 'PORT': '3306', } } typing python manage.py runserver returns the following error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I do in fact have mysqlclient, typing pip install mysqlclient returns the following: requirement already met (1.4.4) I have also tried pip install pymysql And then edited the init.py file to have the following code: import pymysql pymysql.install_as_MySQLdb() Whilst keeping my databases variable the same as above. Doing this produces the following error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. I have the MySQL python connector downloaded and installed onto my system. I have tried giving the empty ALLOWED_HOSTS variable within settings.py an argument of my localhost. The MySQL server is running fine outside of Django and can be accessed on the terminal … -
How can I change the style of marker with Leaflet/Javascript
I have a jquery function that retrieves GeoJSON data from a webpage (created using a GeoDjango server. I want to be able to change the style/color of the marker that it adds. However, when I use the below code, it still shows the standard blue colored marker. New to javascript and leaflet so I'm probably doing something stupid. Eventually, I want to be able to change the style/color based on if the station begins with a "A" or "B" as seen in the geoJSON file below. index.html <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> <title>stations</title> {% leaflet_js %} {% leaflet_css %} <script src="{% static 'dist/leaflet.ajax.min.js' %}"></script> <script src="{% static 'dist/leaflet.ajax.js' %}" ></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <div id="stations" style="height: 450px; width: 100%;"></div> <!--Sets size of map--> <!--{% leaflet_map "cnlnet" %}--> <script> var map = L.map('stations', { center: [42.4444, -76.5019], zoom: 9.5, }); <!--Added OSM base layer below--> var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 20, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }); osm.addTo(map); var stationsUrl = 'stations.data'; $.getJSON(stationsUrl, function (data) { points = L.geoJson(data, { style: function(feature, latlng){ return L.marker(latlng, { icon: L.icon({ iconUrl: "static/img/red.png", iconSize: [28,32], iconAnchor: [12,28], popupAnchor: [0,-25] }) }); } }).addTo(map); }); </script> {% … -
Referencing multiple Django projects from a single monorepo
I want to be able to write shared functions that can be accessed in one-off batch scripts and also by the running Django service (to use the ORM) Currently, I have this in the _init__.py under the my_proj module. if 'DJANGO_SETTINGS_MODULE' not in os.environ: os.environ['DJANGO_SETTINGS_MODULE'] = 'my_proj.blah.blah.settings' import django django.setup() This works fine for one project. However, now I want to do reference the ORM functions from another project, "other_proj". Is there a way to "django.setup()" multiple projects at once? Or, at least, a way to easily toggle the setup between the two projects? Or is there a better way altogether? (I realize I could create a client library to hit the services while they are running, but would prefer to remove that overhead) -
How to represent mpld3 plot(s) in other html file
I am making a plot based on excel-data which is working fine butI'm having problems with the representation of the plot that is made. Currently I'm showing the plot with mpld3.show() import matplotlib.pyplot as plt, mpld3 def speedPlotter(df): ax = plt.gca() df.plot(kind='line',x='time',y='Speed',ax=ax) df.plot(kind='line',x='time',y='Speed1', color='red', ax=ax) df.plot(kind='line',x='time',y='Speed3', color='blue', ax=ax) df.plot(kind='line',x='time',y='Speed5', color='yellow', ax=ax) df.plot(kind='line',x='time',y='Speed7', color='orange', ax=ax) mpld3.show() It plots the dataframe as follows: Now it shows the plot in an ugly plain html page. I want to extend an existing base.html with the plot that has been made but I'm unsure how I should approach it. Is mpld3.fig_to_html(figure) what I should be looking for? -
Access Django model name from admin url pattern
Given an url like: http://127.0.0.1:8000/admin/foo/ How can I access the foo variable from the request, using the request.resolver_match.kwargs ? What kwarg does the admin give too foo? Tried different keys like class, content_type, slug, model, but none of them work. -
Why does ugettext_lazy in rest_auth return a strange value?
I tried to response using ugettext_lazy with this code. return Response({"detail": _("New password has been saved.")}) And the response value I expected is {"detail": "New password has been saved." But the actual return value is { "detail": [ "N", "e", "w", " ", "p", "a", "s", "s", "w", "o", "r", "d", " ", "h", "a", "s", " ", "b", "e", "e", "n", " ", "s", "a", "v", "e", "d", "." ] } Why are all characters returned separated value and wrapped in a list? -
Django nullable ForeignKey causes ProgrammingError
This problem is driving me nuts - I can't spot what's going on so I was hoping that someone would be able to point out what I'm missing here. I've got two sample models, FootballClub, FootballPitch, as defined below. class FootballClub(models.Model) name = models.CharField(max_length=100) class Meta: ordering = ['name'] def __unicode__(self): return self.name class FootballPitch(models.Model): name = models.CharField(max_length=100) owning_club = models.ForeignKey(FootballClub) I've made a modification to the FootballPitch class, more specifically the owning_club field, to add null=True to it, so the class now looks like this; class FootballPitch(models.Model): name = models.CharField(max_length=100) owning_club = models.ForeignKey(FootballClub, null=True) (I don't need to manage this model through a form so I don't care that blank=True is not set). I have also run makemigrations and migrate on this model. When trying to list out all instances of FootballPitch that have owning_club set to null (using FootballPitch.objects.filter(owning_club__isnull=True)) I get the following error; Programming Error: relation "footballclub_footballpitch" does not exist LINE 1: ...d", "footballclub_footballpitch"."name",FROM "footballclub_f... Anyone have any ideas what is going wrong? (Django 1.8.18 and Python 2.7 and postgres 9.8 for reference) Thanks in advance!