Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ElasticSearch DSL DRF aggregations
What is the correct approach to adding aggregations to Django ElasticSearch DSL DRF? The codebase contains some empty filter backends https://github.com/barseghyanartur/django-elasticsearch-dsl-drf/tree/a2be5842e36a102ad66988f5c74dec984c31c89b/src/django_elasticsearch_dsl_drf/filter_backends/aggregations Should I create a custom backend or is there a way to add them directly to my viewset? In particular, I want to calculate the sum of an IntegerField across all results in a particular facet. -
Merge duplicate dictionaries in a list
I have this list of dictionary and I am trying to merge the duplicate dictionaries in the list below is the sample of the list of duplicate dictionary [ { "userName": "Kevin", "status": "Disabled", "notificationType": "Sms and Email", "escalationLevel": "High", "dateCreated": "2019-11-08T12:19:05.373Z" }, { "userName": "Kevin", "status": "Active", "notificationType": "Sms and Email", "escalationLevel": "Low", "dateCreated": "2019-11-08T12:19:05.554Z" }, { "userName": "Kevin", "status": "Active", "notificationType": "Sms", "escalationLevel": "Medium", "dateCreated": "2019-11-08T12:19:05.719Z" }, { "userName": "Ercy", "status": "Active", "notificationType": "Sms", "escalationLevel": "Low", "dateCreated": "2019-11-11T11:43:24.529Z" }, { "userName": "Ercy", "status": "Active", "notificationType": "Email", "escalationLevel": "Medium", "dateCreated": "2019-11-11T11:43:24.674Z" }, { "userName": "Samuel", "status": "Active", "notificationType": "Sms", "escalationLevel": "Low", "dateCreated": "2019-12-04T11:10:09.307Z" }, { "userName": "Samuel", "status": "Active", "notificationType": "Sms", "escalationLevel": "High", "dateCreated": "2019-12-05T09:12:16.778Z" } ] I want to merge the the duplicate dictionaries keeping the value of duplicate keys and have something like this [ { "userName": "Kevin", "status": ["Disabled","Active", "Active"] "notificationType": ["Sms and Email", "Sms and Email", "Sms"] "escalationLevel": ["High", "Low", "Medium"] "dateCreated": "2019-11-08T12:19:05.373Z" }, { "userName": "Kevin", "status": "Active", "notificationType": "Sms and Email", "escalationLevel": "Low", "dateCreated": "2019-11-08T12:19:05.554Z" }, { "userName": "Samuel", "status": ["Active", "Active"], "notificationType": ["Sms", "Sms"], "escalationLevel": ["Low", "High"], "dateCreated": "2019-12-04T11:10:09.307Z" }, ] anyone with a simpler way of achieving this please share your … -
CrashLoopBackOff Error when deploying Django app on GKE (Kubernetes)
Folks, How do I resolve this CrashLoopBackOff? I looked at many docs and tried debugging but unsure what is causing this? The app runs perfectly in local mode, it even deploys smoothly into appengine standard, but GKE nope. Any pointers to debug this further most appreciated. $ kubectl get pods NAME READY STATUS RESTARTS AGE library-7699b84747-9skst 1/2 CrashLoopBackOff 28 121m $ kubectl describe pods library-7699b84747-9skst Name: library-7699b84747-9skst Namespace: default Priority: 0 PriorityClassName: <none> Node: gke-library-default-pool-35b5943a-ps5v/10.160.0.13 Start Time: Fri, 06 Dec 2019 09:34:11 +0530 Labels: app=library pod-template-hash=7699b84747 Annotations: kubernetes.io/limit-ranger: LimitRanger plugin set: cpu request for container library-app; cpu request for container cloudsql-proxy Status: Running IP: 10.16.0.10 Controlled By: ReplicaSet/library-7699b84747 Containers: library-app: Container ID: docker://e7d8aac3dff318de34f750c3f1856cd754aa96a7203772de748b3e397441a609 Image: gcr.io/library-259506/library Image ID: docker-pullable://gcr.io/library-259506/library@sha256:07f54e055621ab6ddcbb49666984501cf98c95133bcf7405ca076322fb0e4108 Port: 8080/TCP Host Port: 0/TCP State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Started: Fri, 06 Dec 2019 09:35:07 +0530 Finished: Fri, 06 Dec 2019 09:35:07 +0530 Ready: False Restart Count: 2 Requests: cpu: 100m Environment: DATABASE_USER: <set to the key 'username' in secret 'cloudsql'> Optional: false DATABASE_PASSWORD: <set to the key 'password' in secret 'cloudsql'> Optional: false Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-kj497 (ro) cloudsql-proxy: Container ID: docker://352284231e7f02011dd1ab6999bf9a283b334590435278442e9a04d4d0684405 Image: gcr.io/cloudsql-docker/gce-proxy:1.16 Image ID: docker-pullable://gcr.io/cloudsql-docker/gce-proxy@sha256:7d302c849bebee8a3fc90a2705c02409c44c91c813991d6e8072f092769645cf Port: <none> Host Port: <none> Command: … -
How to perform split() function inside django template tag?
I need to perform split() function inside django template tag. I tried to do this, but its not working {% for m in us.member %} {% with mv=((m.split(','))[0].split('='))[1] %} <h3 class="media-title"> {{ mv }} </h3> {% endwith %} {% endfor %} Here value of m return a string value 'cn=RND3,ou=Production_test,dc=iss,dc=rndtest,dc=local' Expected output is RND3 -
Forbidden (403) CSRF verification failed. Request aborted. login page not working
i was stuck while creating login page and getting error like "Forbidden (403) CSRF verification failed. Request aborted." please help me out of this Views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from users.forms import UserRegisterForm # Create your views here. def register(request): if request.method=="POST": form=UserRegisterForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') messages.success(request, f"Account created for {username}") return redirect('app1-home') else: form=UserRegisterForm() return render(request, "users/register.html",{"form":form}) Urls.py from django.contrib import admin from django.urls import include, path from users import views as user_views from django.contrib.auth import views as auth_views from app1 import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email=forms.EmailField() class Meta: model=User fields=["username", "email", "password1", "password2"] **login.html** {% extends "app1/base.html" %} {% load crispy_forms_tags %} {% load staticfiles %} {% block content %} <div class="content-section"> <form method="POST" > {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Login</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login </button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Sign Up Here? <a class="ml-2" href="{%url "register" %}">Sign Up</a> </small> </div> </div> {% endblock content %} In setings.py file, I used to write … -
Saving a vector in Django Sqlite3
I am trying to store a vector using Django in Sqlite3 using the following Model Field vector = models.CharField(validators=[int_list_validator(sep=' ', allow_negative=True)], max_length=256) and the corresponding Serializer Field vector = serializers.CharField() Before saving the instance the vector has a shape of (1,128) and on retrieval from database it isn't of required shape. Is it the correct way of saving a vector or an alternate solution exists? -
django-rest-auth "Unable to log in with provided credentials."
If I create a user in django admin and login with that user's correct credentials I fail to have access I do not know why that is. But one more thing, I create user in postman and login it works fine and in django admin it does not work. I think the problem with that, it may be hashing the password because if I type password as user12345 in admin it appear as user12345 but if I do this process in postman it hashes the password like pbkdf2_sha256$150000$W4T5vHbtbI3o$bV+CLOohqcmd0Gi70jcEyRTbOyp45LU5PhBwWHbdCnU= for hashing the password I have this class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) set_password should hashes passwords and I think it may be problem for not logging in my opinion. Any idea please for this issue? Thanks -
data i had posted below and i want to upload it to django model and want to convert the image_link to our local host link
{ "news_by": "Entertainment ", "news_title": "'Sarileru Neekevvaru' teaser: Mahesh Babu is visually pleasing, but Prakash Raj takes the cake again", "news_description": "Mahesh Babu is a pleasure to the eye, much like always, and 'Sarileru Neekevvaru' teaser is high on style quotient too, but Prakash Raj will win you over once again", "image_link":"https://cdn.dnaindia.com/sites/default/files/styles/third/public/2019/11/22/882305-sarileru-neekevvaru-teaser.jpg" } -
Django Query first ForeignKey of an object in a query
Trying to run a query on ordered store instances by distance, and then query the first Foreignkey Coupon of each store Instance. I am trying to show a coupon from each nearby store. models.py ... class Store(models.Model): location = models.PointField(srid=4326, null=True, blank=True) class Coupon(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name='store') views.py class homeView(View): def get(self, *args, **kwargs): store_nearby = Store.objects.annotate(distance = Distance("location", user_location)).order_by("distance") context = { 'store_list': store_nearby, # 'offer': offer, } return render(self.request, 'mysite/home_page.html', context) home_page.html {% for object in store_list %} {% for coupon in object.offer.first %} // This doesnt work {{ coupon.title }} {% endfor %} {% endfor %} -
switch user in django
I have django server installed under ownership of user say 'X'. Now I want to switch to user 'Y' and execute some scripts. Currently for changing user I am using sudo su "Y" -c "commands to execute" . I have added user "X" in sudoers file so that now it does not ask for a password. Is there any way to do it without sudo.I have already tried it by editing /etc/pam.d/su file so that it does not ask for password when user X runs "su Y" without sudo. Is there any other way in which this can be achieved? -
"ImportError: DLL load failed while importing _openmp_helpers"?
I tried to import resample_img from nilearn.image to use in resampling some medical image. import nibabel as nib import nibabel.processing from nilearn.image import resample_img img = nib.load('./dicom_to_nifti.nii') new_img = nibabel.processing.resample_to_output(img, (2, 2, 2)) new_img.to_filename('nifti_2_2_2') However I keep getting this error that says that it can't find the sklearn module? I've installed it already via pip install sklearn. I've even tried to uninstall everything and get a fresh install but the same problem pops up. I'm certain it's either I'm doing something wrong, or there's something wrong with the packages. Traceback (most recent call last): File "convert.py", line 9, in <module> from nilearn.image import resample_img _check_module_dependencies() File "C:\Users\craig\AppData\Local\Programs\Python\Python38\lib\site-packages\nilearn\version.py", line 111, in _check_module_dependencies _import_module_with_version_check( File "C:\Users\craig\AppData\Local\Programs\Python\Python38\lib\site-packages\nilearn\version.py", line 60, in _import_module_with_version_check module = __import__(module_name) File "C:\Users\craig\AppData\Local\Programs\Python\Python38\lib\site-packages\sklearn\__init__.py", line 75, in <module> from .utils._show_versions import show_versions File "C:\Users\craig\AppData\Local\Programs\Python\Python38\lib\site-packages\sklearn\utils\_show_versions.py", line 12, in <module> from ._openmp_helpers import _openmp_parallelism_enabled ImportError: DLL load failed while importing _openmp_helpers: The specified module could not be found.. Module "sklearn" could not be found. See http://nilearn.github.io/introduction.html#installation for installation information. PS C:\Users\craig\Documents\Files\westmead_radiomics> python test.py Traceback (most recent call last): File "test.py", line 3, in <module> from nilearn.image import resample_img File "C:\Users\craig\AppData\Local\Programs\Python\Python38\lib\site-packages\nilearn\__init__.py", line 72, in <module> _check_module_dependencies() File "C:\Users\craig\AppData\Local\Programs\Python\Python38\lib\site-packages\nilearn\version.py", line 111, in _check_module_dependencies _import_module_with_version_check( File … -
Heroku Django requests static files that don't exist
Using whitenoise for managing production static files. Django==2.1.4 whitenoise==4.1.2 My production server is requesting static files that look like mine (ie bootstrap.min.js) but have characters on the end (ie. bootstrap.min.xyz789). I notice that in my STATIC_ROOT directory there are already a bunch of these (ie. bootstrap.min.abc123) but they don't match the ones that my heroku site is requesting (ie. bootstrap.min.xyz789). I ran collectstatic both locally and in heroku but no luck. What are these files and why don't they match? PS - no issue locally only in heroku. -
How to connect both website and android application into one firebase database
I am having trouble on how will I access all the information needed because I am creating an android application and a website having the same data in it. I want to see that the data I enter in the android app will also appear in the website I have made. -
How to redirect tenant to subdomain
I am using django-tenant-schemas to add multi-tenancy to my SaaS website but have not found a good way to redirect tenants to their subdomain automatically. I am wondering what others have done in this same scenario? I have asked in the repo but no responses and am not seeing anything in the docs after reading it several times. Also, cannot find any info in searches which is quite surprising. Anybody have thoughts on this? -
How can i give form and field validation to my fields?
I want to add some validation if user try to register or login he must go through some restrictions. Please help me someone as i am new to django models.py class Post(models.Model): STATUS_CHOICES=(('draft','Draft'),('published','Published')) title=models.CharField(max_length=264) slug=models.SlugField(max_length=264,unique_for_date='publish') author=models.ForeignKey(User,related_name='blog_posts',on_delete=models.PROTECT) body=models.TextField() publish=models.DateTimeField(default=timezone.now) created=models.DateTimeField(auto_now_add=True)#datetime of create() action updated=models.DateTimeField(auto_now=True)#datetme of save() action status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') forms.py I used to write forms like this instead of modelforms. If someone try to register then he must obey some rules that like password characters and length, username should be right like that. registration form class RegisterForm(forms.Form): first_name = forms.CharField( label='First name ', widget=forms.TextInput( attrs={ 'class':'form-control', 'placeholder':'Enter your first name' } ) ) last_name = forms.CharField( label='Last name ', widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter your last name' } ) ) GENDER_CHOICE = ( ('male', 'Male'), ('female', 'Female') ) gender = forms.ChoiceField( widget=forms.RadioSelect(), choices=GENDER_CHOICE ) username = forms.CharField( label='User name ', widget=forms.TextInput( attrs={ 'class':'form-control', 'placeholder':'Enter your user name' } ) ) password1 = forms.CharField( label='Password ', widget=forms.PasswordInput( attrs={ 'class':'form-control', 'placeholder':'Enter your password' } ) ) password2 = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ 'class':'form-control', 'placeholder':'Re-enter your password' } ) ) email = forms.EmailField( label='Email-id', widget=forms.EmailInput( attrs={ 'class':'form-control', 'placeholder':'Enter your email id' } ) ) mobile = forms.IntegerField( label='Mobile ', widget=forms.NumberInput( attrs={ 'class':'form-control', 'placeholder':'Enter your … -
ReactJS not displaying Django REST Framework API data
I am trying to use ReactJS to build a simple website that pulls data from my Django REST Framework API. The issue I am running into, is that my data is not being output by React. I am certain that my Django backend is running flawlessly. I get no errors when running it, and can view my API data via "http://127.0.0.1:8000/api/". Here is my frontend ReactJS code: import React, { Component } from 'react'; class App extends Component { state = { usernames : [] }; async componentDidMount() { try { const res = await fetch('http://127.0.0.1:8000/api/'); const usernames = await res.json(); this.setState({ usernames }); } catch (e) { console.log(e); } } render() { return( <div> {this.state.usernames.map(item => ( <div key={item.id}> <h1>{item.username}</h1> </div> ))} </div> ); } } export default App I have tried updated my CORS_ORIGIN_WHITELIST via settings.py and includes all variations of localhost. When scripting with Python, I am able to make a request and retrieve my API data. This is the output: [{'username': 'testname', 'created_at': '2019-12-06T00:03:50.833429Z'}, {'username': 'testname2', 'created_at': '2019-12-06T00:04:01.906974Z'}, {'username': 'testname3', 'created_at': '2019-12-06T00:04:05.330933Z'}, {'username': 'testname4', 'created_at': '2019-12-06T00:04:08.144381Z'}] And though no ID is present in the output (Which I'm not sure why) I can still access the correct … -
Django infinite scroll messed up design. CSS need correction
I am developing one website using Django. The website link is, http://34.66.79.236/listings/ You can see that the tiles on the website has got overlap on each other. This happened after I implemented infinite scroll. I found it at below link, https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html If you scroll down you will see more and more properties are getting loaded. At a time I am loading 20 listings. But not sure what has gone wrong. I know there is something wrong with CSS but I am not sure what it is. Please guide. -
File (.tar.gz) download and processing using urlib and requests package-python
SCOPE: Which library to use? urllib Vs requests I was trying to download a log file available at a url. URL was hosted at aws and contained file name as well. Upon accessing the url it gives a .tar.gz file to download. I needed to download this file in the directory of my choice untar and unzip it to reach the json file inside it and finally parse the json file. While searching on internet I found sporadic information spread all over the place. In this Question I try to consolidate it in one place. -
I can't get parent page query in wagtail
I have tried this code but always return an empty query, and i don't know why. parent = MangaPage.objects.filter(title=Page.get_parent) -
403 from Jquery in Django
Yes, I have learned that it has to do with the csrf stuff, yet none of the copypaste I have found around has worked. (example below) The second question I ask myself is that I dont seen how from the jquery code can you actually connect to a function in a view by just indicating the url of the page. there are a lot of functions in the views.py file. How does it know to which it has to go? Just because you write extra code in the view function? It will have to go and check all functions? So here is the jquery: I get a 403 when clicking on the radio button to send the word. $(document).ready(function(){ $('input[type="radio"]').click(function(){ var valor = $(this).val(); data: "{'csrfmiddlewaretoken': '{{csrf_token}}' }", $.post('/', JSON.stringify({valor:valor}), function(data){ }); }); }); -
pythonanywhere // python manage.py collectstatic = 0 static files copied to // 175 unmodified
CMD /PruebaApettito.FINAL/PruebaApettito.FINAL-master/Prueba2/proyectoapettito (master)$ python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /home/sagutierrezr95/PruebaApettito.FINAL/PruebaApettito.FINAL-master/Prueba2/proyectoapettito/AppApettito/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Found another file with the destination path 'admin/js/collapse.min.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. ... 0 static files copied to '/home/sagutierrezr95/PruebaApettito.FINAL/PruebaApettito.FINAL-master/Prueba2/proyectoapettito/AppApettito/static', 175 unmodified. SETTING ALLOWED_HOSTS = ['sagutierrezr95.pythonanywhere.com'] STATIC_URL = '/static/' STATIC_ROOT = '/home/sagutierrezr95/PruebaApettito.FINAL/PruebaApettito.FINAL-master/Prueba2/proyectoapettito/AppApettito/static/' I need the templates on my page but I have no idea what I am doing wrong. the route should be correct and not misspelle -
Why am I getting this error "local variable 'text' referenced before assignment"
I am trying to create a share function using python and Django and when I run "share" it gives me back an error. Here's my code: views.py from django.shortcuts import render from basicapp.forms import UserForm, UserProfileInfoForm, PostForm from django.contrib.auth.models import User from basicapp.models import UserProfileInfo from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth import login,logout,authenticate @login_required def user_post(request): form = PostForm(request.POST) if form.is_valid(): text = form.cleaned_data['post'] form = PostForm() return HttpResponseRedirect(reverse('index')) else: HttpResponse("Not Valid try dat boi agian") render(request, 'basicapp/userpost.html', {'form':form, 'text':text}) forms.py class PostForm(forms.Form): post = forms.CharField(max_length=256) This is the error: -
I cant get this angular authentication using token to work
There is an App x and App z. App x is a django application. App z is an Angular application. I want a scenairo where if the link to app z is clicked from App x, the token of that user is sent with the url, then stored in session storage and the user data is gotten and stored in storage also. -
Nested Caching in Django
I have an HTML partial, which has a background image that Id like to cache. The partial itself contains dynamic content, though, so I cant cache the whole partial. Is there any way around this with Memcached in Django? Is there another way of accomplishing this? -
How to solve ModuleNotFoundError: No module named 'mass' (from gmane)
System info: pip3 --version pip 19.3.1 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7) python3 --version Python 3.7.1 sw_vers ProductName: Mac OS X ProductVersion: 10.15.1 BuildVersion: 19B88 Trying to install Mass module to resolve the traceback shown below in the Django project as shown below. python3 manage.py check Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line …