Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
"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 … - 
        
Django Pytrends calling results Type Error Object of type QuerySet is not JSON serializable
Firstly, I have looked at previous documentation from previous questions, but they are not super similar. In pytrends, you have TrendReq, and then build payload which requests the data from google trends. I am having trouble with having User Input from a form field in Django. I created a model form to store the queries which I will be using for some other things. However, whenever I try to pass a user input, the payload never gets built due to this error saying it is not JSON serializable. So in this case I am thinking it is two things: I have an issue with my user input. TrendReq already requests the information, therefore I do not need to have a request function in my views Here are the three pieces of relevant code: forms.py class TrendForm(ModelForm): class Meta: model = trendParams fields = ['trends'] widget = {'trends': TextInput(attrs={'class': 'form-control', 'placeholder': 'Look Up'})} views.py (where I call) def pytrends_query(request): form = TrendForm() trendData = [] all_trends = trendParams.objects.all() pytrends = TrendReq(hl='en-US', tz=360)#calls pyTrends kw_list = [all_trends] #calls form from forms.py for user input from HTML file pytrends.build_payload(kw_list, cat=0, timeframe='now 7-d', geo='US-MA', gprop='') #builds payload for request req = pytrends.related_queries() #calls related … - 
        
Django html page wont allow post with multiple items
I have a html page that runs a for loop to populate students on a board. Here is screenshot and the code. Issue: The issue is if i have more than one student in the class , no matter which button on the page i click it will not let me do a POST. If there is just a single kid in the class, the POST will work. So the post is failing and i don't know why. Thanks for the help in advance. {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy K8Points_ClassroomForm %} {% load static %} {% block content %} <br> <h2>{% load static %} <img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> My Classroom</h2> <br> <br> <form action="/points/k8_points_classroom" method="POST"> {% csrf_token %} <!-- Start Date --> <div class="container"> <div class="container"> <div class='row'> <div class="col-4"> <p> Recording Data as User : {{user.username}} </p> <p><b> Classroom : {{class_name}} </b></p> </div> </div> <div class='row'> <div class = "col-2"> {{form.date|as_crispy_field }} </div> <div class = "col-2"> {{form.week_of|as_crispy_field }} </div> <div class = "col-2"> {{form.day|as_crispy_field }} </div> </div> </div> <div class="jumbotron" align="middle"> <h1>My Students</h1> <!-- Line Break --> <hr style="border: 1px solid black;"/> <!-- Line Break --> <div class="row mb-3"> … - 
        
How can two Python applications hosted in different servers communicate?
I'm having an hard time figuring out how to solve a problem with a little project. Basically i have a Django application. On the other hand i have an external Python script running. I would like to create a system where, each time a form in my Django app is submitted, the data submitted in the form is sent to the external Python application. The external Python service should receive the data, read it, and according to who is the user and what did he submit, it should perform some tasks, then send a response. Here is what i thought: 1) Connect the external Python app to the same database that Django is using. So that when the form is submitted, it is saved on the database and the data can be 'shared' with the second Python service. The problem with this solution is that i would need the second app to query the Database every second and perform a lot of queries, that would be a problem with performances. 2) Create an epi endpoint, so that the external python app would connect to the endpoint and fetch the data saved in the database from there. The problem is the … - 
        
How to stop quotes JSON from being escaped in a Django template?
How do you stop quotes from being escaped in a Django template? I'm trying to render a Python dictionary, representing Javascript options. My Django view's context retrieval method looks like: def get_context(self): context = {'options': mark_safe(json.dumps({'name': 'value'}))} return context and my template looks like: <html> <script>new SomePlugin.Object({{ options }});</script> </html> but for some reason, it renders like: <html> <script>new SomePlugin.Object({\"name\": \"value\"});</script> </html> For some reason, it's inserting backslashes to escape the quotes, as though it was rendering the data inside a string. Since it's not inside a string, this results in malformed Javascript. However, I can't find any way to disable this escaping. How do I do this? I thought that's what mark_safe did, but that's having no effect, and neither does {{ options|safe }}. - 
        
How to add 'Delete' button to User Profile view in Django app?
I have an app login/logout system in which I automatically generate user profiles once user is registered. My Profile.html looks like this: <div class="col s12"> <form method="POST"> {% csrf_token %} <fieldset class=""> <legend class="">Profile Info</legend> {{ u_form.username }} {{ p_form.postcode }} </fieldset> <div class="col s6"> <button class="btn" type="submit">Update</button> </div> </form> /div> and my profile function from views like this: @login_required def profile(request): if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f"Account updated!") return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = {"u_form": u_form, "p_form": p_form} return render(request, "users/profile.html", context) How do I add a 'Delete' button and function to allow user delete his/fer own profile to no longer exist in my database? - 
        
Difference between UpdateView and BaseUpdateView - Django
My Doubt is: Difference between UpdateView and BaseUpdateView and how to use them I have tried to find information on the subject, but it is not much, so I have the doubt how to use exactly the BaseUpdateView view and similar views. Thanks in advance for your answers! - 
        
Django get() missing 1 required positional argument: 'header'
Every time i do a successful post request i get this message. I know it has something to do with implementing the redirect function so you don't get a double post, but i cant get it to work right. Here is my code. Thanks for the help. @login_required def K8_Points_Test(request): if request.method == 'POST': form = K8PointsTestForm(request.POST) if form.is_valid(): form.save(commit=False) class_name = form.cleaned_data.get('class_name') getstudents = Student.objects.filter(class_name = class_name) students = getstudents.all() context = {'form': form ,'students' : students , 'class_name': class_name} return render(request, 'points/k8_points_test.html', {'form': form} ) else: return HttpResponseBadRequest else: form = K8PointsTestForm() return render(request, 'points/k8_points_test.html', {'form': form} ) - 
        
Passing a value from html template to views.py in Django
can you please help me with the issue I'm experiencing? Basically, I followed a tutorial online to create a location-based application that displays the shops around the user's location. However, the longitude and latitude are hard-coded in views.py. views.py from django.http import request, HttpResponse from django.views import generic from django.contrib.gis.geos import Point from django.contrib.gis.db.models.functions import Distance from .models import Shop longitude = 10.113 latitude = -2.231 user_location = Point(longitude, latitude, srid=4326) class Home(generic.ListView): model = Shop context_object_name = 'shops' queryset = Shop.objects.annotate(distance=Distance('location', user_location) ).order_by('distance')[0:15] template_name = 'shops/index.html' I added the Leaflet integration with my template so now I can I have access to the latitude and longitude variables which I need to pass back to my views.py and update them there. Is that possible in general and what you be the solution for this? Thank you a lot for the help index.html map.locate({setView: true, maxZoom: 16}); function onLocationFound(e) { var radius = e.accuracy; var lat = e.latlng.lat; var lon = e.latlng.lng; L.marker(e.latlng).addTo(map) .bindPopup("You are within " + radius + " meters from this point"+ +lat+lon).openPopup(); L.circle(e.latlng, radius).addTo(map); } - 
        
500 Server Error Serving Static with Whitenoise
Apologies for the length of code in this, I wanted to make sure I include as much as necessary for troubleshooting purposes. I have a Django application that needs to serve static files in production, and I've chosen whitenoise because it A) was built to do exactly that and B) seems like the simplest to configure. I've followed the steps in the documentation and this medium article and this blog post but I'm still seeing a 500 server error. I don't have any more details than that, I'm not getting a stack trace error and the page just says 500 server error. I'm at a loss as to what I'm doing wrong to get this to work. The only difference I can see between what I'm doing and what the blogs are doing is that my application is built in a Docker container. Any help would be much appreciated! settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STAT = os.path.join(BASE_DIR, 'static') DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'audit_tool', 'rest_framework', 'crispy_forms', 'bootstrap', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] WSGI_APPLICATION = … - 
        
Invalid template library specified. ImportError raised when trying to load 'compressor.templatetags.compress': cannot import name 'six'
I'm trying to add .scss to project by this tutorial. With Django 2 it works fine. But with Django 3.0 I'm getting an error. I'm creating new project with django-admin startproject mysite Then doing this part of tutorial https://prnt.sc/q6qyy2, and getting this error: File "/home/yuriy/Desktop/my/mysite/env/lib/python3.6/site-packages/django/template/backends/django.py", line 125, in get_package_libraries "trying to load '%s': %s" % (entry[1], e) django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'compressor.templatetags.compress': cannot import name 'six' my pip freeze output: asgiref==3.2.3 Django==3.0 django-appconf==1.0.3 django-compressor==2.3 django-libsass==0.7 libsass==0.19.4 pkg-resources==0.0.0 pytz==2019.3 rcssmin==1.0.6 rjsmin==1.1.0 six==1.13.0 sqlparse==0.3.0 Appreciate any help. Thanks