Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django - what is the best way to avoid doing repetitive queries in a dynamic navbar?
I'm currently developing a project which has two apps. When the user logs into the system, the navbar will show the links according to what permissions the user has in the database. If the user only has permissions for app 1, the links it will show will only correspond to this app, the same if it only has permission for app2. If the user has permission for both the navbar will show all the links of both apps. Being dynamic the navbar has to make queries to the database. so I want to avoid making a query every time a page is loaded. I have thought that an option is, in the view, to make the query a first time and then store it with request.session: Try: #If the query has already been made, it accesses the saved value query = request.session['navbar'] Except: # If the query has not been made, makes it and saves it in request.session['navbar'] request.session['navbar'] = #QUERYCODE This is a good way to handle the problem? is there another better way? -
How to filter a query on Django ORM
I know this should be pretty basic but somehow I don't quite get it. I want to get all users which age is lesser than 18 so the query should be something like this User.objects.filter(age < 18) what Im doing wrong? -
Django - If i put 2 formsets together in my view, the function to add multiple times the same views doesnt work
I have this code bellow. Im using formset to add multiple times the same form. But if i put this 2 formsets together, like in my view, just the first data for each form is saved. And if i put just 1 formset in my def, it works, all datas for i put to the form is saved. Someone have any idea why this is happening? (sorry for my eng) Forms.py class InsereIdioma(forms.ModelForm): class Meta: model = Idioma fields = '__all__' exclude = ['usuario'] InsereIdiomaFormset = formset_factory(InsereIdioma, extra=1) class InsereTecnologia(forms.ModelForm): class Meta: model = Tecnologia fields = '__all__' exclude = ['usuario'] InsereTecnologiaFormset = formset_factory(InsereTecnologia, extra=1) Views.py def cadastro_curriculo(request): if request.method == 'GET': formset_idioma = InsereIdiomaFormset(request.GET or None) formset_tecnologia = InsereTecnologiaFormset(request.GET or None) elif request.method == 'POST': formset_idioma = InsereIdiomaFormset(request.POST) formset_tecnologia = InsereTecnologiaFormset(request.POST) if formset_idioma.is_valid(): for form in formset_idioma: idioma = form.cleaned_data.get('idioma') fluencia = form.cleaned_data.get('fluencia') if idioma and fluencia: Idioma( idioma=idioma, fluencia=fluencia, usuario=request.user ).save() if formset_tecnologia.is_valid(): for form in formset_tecnologia: sistema = form.cleaned_data.get('sistema') nivel = form.cleaned_data.get('nivel') if sistema and nivel: Tecnologia( sistema=sistema, nivel=nivel, usuario=request.user ).save() return render(request, "personal/curriculo.html", { 'formset_idioma': formset_idioma, 'formset_tecnologia': formset_tecnologia, }) -
Post HTML input tag file data to another input tag file and retrieve in Django views
I'm trying to send one <input type="file"... value to another <input type="file".. using Javascript. I've created an HTML form and after filling it, I want to review the form. Then submit that form in my FormFill model through views.py. So far what I have done is creating 2 different Divs for the same work. In div1, I'm sending my form data using action="javascript:reviewForm()" and in reviewForm(), I'm setting all the form data of div1 to div2 form using document.getElementById('cfname2').value = document.getElementById('cfname1').value; It's setting all the values and then posting it to views.py successfully except my <input type="file" name="pic2".. data. Since python retrieves form POST data using request.FILES['pic2'], in div2 I don't have file data to Post. So far what I've tried is: document.getElementById('pic2').value = document.getElementById('pic1').value; where, In div1 I have <input type="file" id="pic1"... and in div2, <input type="file" id="pic2"... My models.py class FormFill(models.Model): pic = models.ImageField(upload_to='candidates/pics/') ... How can I post the div2 image data to views and then to Django models? Note: I don't want to Post the div1 data directly to Django models since I want my users to first review the form that they have filled. And that's why using the concept of 2 Divs. Thanks in … -
Chaining querysets in managers
I am looking for a way to reuse this abstract model/manager with queryset on the models that require soft delete but some of my models already have custom managers/querysets. Ideally I would like all of those other managers to use SoftDelete manager/queryset so that they would always return only undeleted items. Is there a way to achieve this in Django 1.10? class SoftDeleteQuerySet(QuerySet): def delete(self): for obj in self: obj.is_active = False obj.save() def undelete(self): for obj in self: obj.is_active = True obj.save() class SoftDeleteManager(Manager): def get_queryset(): return SoftDeleteQuerySet(self.model, using=self._db).filter(is_active=True) class SoftDelete(Model): is_active = m.BooleanField(default=True) objects = SoftDeleteManager() class Meta: abstract = True def delete(self): self.is_active = False self.save() def undelete(self): self.is_active = True self.save()