Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using values in html to scripts (Django, Mapbox)
I am making an app using Django and Mapbox. Here is my code that I have a question about: {% for center in drop_in_centers} <script> new mapboxgl.Marker({ "color": 'red' }) .setLngLat([-73.959, 40.795]) .setPopup(new mapboxgl.Popup().setHTML("<h1>Manhattan</h1><h2>New York, NY</h2>")) .addTo(map) </script> {% endfor %} I am trying to use the values of drop_in_centers in the script that I have in my html code. drop_in_centers is a list from a JSON file as below: [{'center_name': 'Living Room', 'borough': 'Bronx', 'address': '800 Barretto Street; Bronx, NY\n10474', 'comments': 'Open 24 hours', 'postcode': '10474', 'latitude': '40.816615', 'longitude': '-73.889883', ......}] So I want to use the latitude and longitude to fill up the value for setLngLat([XX.XXX, XX.XXX]) and other values to populate .setHTML("XXXXXXXXX") How can I do this? -
Get Reverse of ManyToMany Relation with self
I am trying to create a basic quora clone. I have the following which is my custom user model: models.py class Author(AbstractBaseUser): ... followers = models.ManyToManyField("self", related_name="following", symmetrical=False) ... objects = AuthorManager() I have the following two views trying to get the followers a user has (this one works) and the users the current user is following. class AuthorFollowersAPIView(ListAPIView): #This One Works! serializer_class = AuthorMinSerializer lookup_field = "username" def get_queryset(self, **kwargs): username = self.kwargs["username"] print("followers") return Author.objects.get(username=username).followers.all() class AuthorFollowingAPIView(ListAPIView): #This Doesn't Work serializer_class = AuthorMinSerializer lookup_field = "username" def queryset(self, **kwargs): username = self.kwargs["username"] return Author.objects.get(username=username).following.all() How can I get the AuthorFollowingAPIView to work the way I want it to? -
Django Rest: CORS policy: No 'Access-Control-Allow-Origin' block only one api endpoint
I am using Django 3.1.2 and djangorestframework==3.12.1. I have 32 APIs, among them, all works fine except one. Yeah, Only One API showing this error Access to XMLHttpRequest at 'https://url.com/api/scraping/' from origin 'https://url.web.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Here is django-cors-headers(3.5.0) setup INSTALLED_APPS = [ 'django.contrib.admin', ... 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'api', ] MIDDLEWARE MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Others CORS_ORIGIN_ALLOW_ALL = True CSRF_TRUSTED_ORIGINS = [ 'url.web.app', 'https://url.com/', #server "127.0.0.1", 'localhost' ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = default_headers + ( 'Access-Control-Allow-Origin', ) Using this setting 31 API works fine among 32, only 1 API getting blocked. I am using react as frontend, here it the code for accessing API export function postCvScraping(token, userID, jdID) { const formData = new FormData(); formData.append("userID", userID); formData.append("jdID", jdID); const config = { headers: { 'Authorization': "Token " + token, 'Content-Type': 'application/json', "Access-Control-Allow-Origin":"*" } } return instance.post("scraping/", formData, config) } Some people suggest to add this line "Access-Control-Allow-Origin":"*". But not working my case. -
How to save dynamically added fields to a form in a model in Django?
I needed to add new fields to a ModelForm when the user clicks on a button and I accomplished that by overriding the init method. def __init__(self, *args, **kwargs): extra_fields = kwargs.pop('extra', 0) super(Form, self).__init__(*args, **kwargs) self.fields['extra_field_count'].initial = extra_fields for index in range(int(extra_fields)): print('loop') # generate extra fields in the number specified via extra_fields self.fields['extra_field_{index}'.format(index=index)] = \ forms.CharField() This seems to work as I'm not getting any errors and the form is valid but I now want to know on how to save the additional fields to my model. -
Wagtail: Problem with multiple ParentalKey fields
I have two models in Wagtail that are set up to be related to each other via ParentalKey fields. I've noticed that this seems to cause problems when trying to publish changes to an entry in the parent model. My models.py looks something like this: class Person(Page): (field definitions here) class ResearchTask(Page): task_contact = ParentalKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_task_contact_list') task_manager = ParentalKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_task_manager_list') (other field definitions here) When I edit a ResearchTask and assign a person as task_manager, and then edit the Person, even if I make no changes and simply click Publish, I'll get an error like the following: ValidationError at /admin/pages/2172/edit/ {'live_revision': ['page revision instance with id 369 does not exist.']} What's weird is that this revision id refers to a record that does exist and is fact the published revision for the ResearchTask. What's even weirder is that I never have this problem with the first of these two fields, task_contact. Only task_manager seems to cause the revision error. I can assign the same person as both task_contact and task_manager, and only run into an issue with the manager field, and if I remove the task_manager field from the database completely by deleting it … -
Add variable to Django request object in Middleware (once)
class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) request.variable = 1 response = self.get_response(request) return response This works but it it processing the request twice. I am unsure of how to set this variable after the view has been processed (for every view), only once. process_template_response is not a valid option because it will not work with every view. Is there a better way to do this? -
redis in django doesn't set cache object
According to this django redis example, I do everything this article said. But when I run the project, it never does cache the products. I add two print statement in the views.py: @api_view(['GET']) def view_cached_books(request): if 'product' in cache: print('get') products = cache.get('product') return Response(products, status=status.HTTP_201_CREATED) else: print('set') products = Product.objects.all() results = [product.to_json() for product in products] cache.set(products, results, timeout=CACHE_TTL) return Response(results, status=status.HTTP_201_CREATED) when I go to localhost and refresh the page, it always prints set in the console. I already started the redis-server and tested the server by redis-cli, also did set the CACHES in the settings.py: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, } } and set the INTERNAL_IPS too: INTERNAL_IPS = [ '127.0.0.1:8000', ] and updated the MIDDLEWARE: MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] Can anyone tell me where is the problem? Thanks in advance. -
Getting django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.10.1. error whille using mysql in dajngo
I am using dajngo 3.1.0 and i get this error when i use mysql as database on deploy server. My server is apache server and uses Cpanel. I have tried installing mysqlclient and PyMySQL and adding below code to __init__.py file. import pymysql pymysql.version_info = (1, 3, 13, "final", 0) pymysql.install_as_MySQLdb() -
how to sum in django model fields
I have two models here one is contains subject info and another one course info, i want to sum how many credits(total) have in this course,to show in template. i have tried but didn't work. thank you so much class Course(models.Model): name = models.CharField(max_length=200, unique=True) prefix = models.CharField(max_length=20) code = models.CharField(max_length=20) subject = models.ManyToManyField('Subject', related_name='subject_list', blank=True) def tota_credit(self): total = 0 for cred in self.subject_set.all(): total += cred.credit return total # doesn't work :( def __str__(self): return self.name another model class Subject(models.Model): name = models.CharField(max_length=50) code = models.PositiveIntegerField(unique=True) credit = models.IntegerField(blank=True) def __str__(self): return self.name views.py class Course_detail(generic.DetailView): model = Course template_name = 'course_detail.html' context_object_name = 'queryset' def get_context_data(self, **kwargs): self.profile = Student.objects.all() context = super().get_context_data(**kwargs) context['profile'] = self.profile return context -
how to fix Error during template rendering
enter code here enter code here widget_tweaks' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz 1 {% extends "poll/base.html" %} 2 {% load widget_tweaks %} Blockquote -
Django - Automatic task performace at specific time
My app consists of posts with upvote counter. I would like to set automatic task for Django to zero upvote counter for each post at midnight. What is the best way to achieve it? Is there any built-in or external libraries for such purposes? -
Graphviz django probelm
I'm a Python Developer currently in the process of making a family website. I am developing a website using the Django framework in Python. I have planned to make an interactive family tree using the Graphviz package in Django. I am able to create a .SVG graph for the family tree from the Python command terminal directly. But when I integrate Grapgviz with Django using django-extensions, it is NOT working. Without implementing this family tree, my website can not be complete. Has anyone in the users group faced similar problems? Any help in this regard will be highly appreciated -
Error Failed to import test module: tests.test_models prints when using python tests in Pycharm
I am having an issue which throws the following error when I go to run tests in pycharm: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. It appears the issue is with pycharm as I just ran ./manage.py test and the tests executed successfully. I have sifted through SO and have tried everything from modifying imports, checking INSTALLED_APPS, and ensuring the configurations are ok for the Python unittests. Nothing Project Hierarchy Configurations which I have set using pycharm are: Script path:/MainFolder/MainProjects/project1-backend/tests Environment Variables: PYTHONUNBUFFERED=1; DJANGO_SETTINGS_MODULE=project1backend.settings note the folder to which this belongs to is project1backend not project1-backend Python interpreter: Python 3.8(MainFolder) ~/MainFolder/MainProjects/bin/python Working Directory:/Users/myname/MainFolder/MainProjects/project1-backend Add contentroots to PYTHONPATH: notselected Add source roots to PYTHONPATH: selected Error Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/case.py", line 60, in testPartExecutor yield File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/case.py", line 676, in run self._callTestMethod(testMethod) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/case.py", line 633, in _callTestMethod method() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 34, in testFailure raise self._exception ImportError: Failed to import test module: tests.test_models Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/myname/MainFolder/MainProjects/project1-backend/tests/test_models.py", line 2, in … -
Django compilemessages not discovering 3rd party apps
For some reason, Django's compilemessages is not discovering the locale folders of the 3rd party apps I have installed. Here is my basic project structure: project - setup.py - requirements.txt - virtual environment - project_name - apps - manage.py - translation - project_name - settings The locale_paths are set to LOCALE_PATHS = os.getenv('LOCALE_PATHS', BASE_DIR + '/translation'), When running manage.py makemessages and compilemessages on my localhost, from the base directory where manage.py is located, it will only discover the translation folder, but moving one level up to the project folder and running project_name/manage.py compilemessages will discover and compile the translation folder as well as any installed 3rd party apps' locale folders. This would be fine, if slightly strange, if it worked consistently, but this solution does not hold when we run the build script to deploy to a server. Even when moving up a level, compilemessages will only discover the translation folder with our custom translations and not any 3rd party apps. Does anyone know what could be causing this problem? -
Readability Django app, issues sending results to model
Im trying to analyze a text provided by the user via a form input, that text is saved on a model, and then analyze it to finally show the results on a results.html, and save the info on the results model. --------- VIEWS.PY ---------------------- from django.shortcuts import render from django.http import HttpResponseRedirect from .models import TestedText, TestResults from textatistic import Textatistic import time # Create your views here. def readtest(request): return render( request, 'test.html' ) def addtext(request): a = TestedText(title=request.POST['title'], content=request.POST['content']) a.save() def result(request): text = addtext(content) s = Textatistic(text) r = TestResults( Flesch = (s.flesch_score, request.POST['Flesch']), DaleChall = (s.dalechall_score, request.POST['DaleChall']), Fleschkincaid = (s.fleschkincaid_score, request.POST['Fleschkincaid']), gunningfog = (s.gunningfog_score, request.POST['gunningfog']), smog = (s.smog_score, request.POST['gunningfog']) ) r.save() return render(request, 'results.html') ----------- MODEL.PY --------------------------------------- from django.db import models # Create your models here. class TestedText(models.Model): title = models.TextField(max_length=50, default=None) content = models.TextField(max_length=500, default=None) class TestResults(models.Model): character_count = models.IntegerField(default=None) DaleChall_list = models.IntegerField(default=None) polysylables = models.IntegerField(default=None) sentences = models.IntegerField(default=None) sybles = models.IntegerField(default=None) words = models.IntegerField(default=None) Flesch = models.IntegerField(default=None) DaleChall = models.IntegerField(default=None) Fleschkincaid = models.IntegerField(default=None) gunningfog = models.IntegerField(default=None) smog = models.IntegerField(default=None) -
How do I 'Move' a whole Django project 'down' a URL prefix i.e. (localhost ---> localhost/APP_NAME/)?
I'm aware I'm probably not using the correct terminology, but when i developed my Django project it would sit on the root URL i.e. http://localhost whereas now I'm moving it into production it needs to sit - http://localhost/APP_NAME This is the structure of my project APP_NAME ----APP_NAME ----SECOND_APP I've tried the following, from APP_NAME/urls.py to get to SECOND_APP - ORIGINAL ATTEMPT path('', include('second_app.urls')) --to--> url(r'^APP_NAME/', include('second_app.urls')), but I keep getting a 404 error, so it's obviously not working! In SECOND_APP/urls - path('', login_required(views.home), name='SECOND_APP'), Where am I going wrong here? -
Is it possible to create the database prior to django running any migration commands?
I spun up a MySQL database but I've noticed I have to manually connect to it and run CREATE {DB} and then run my migrations. If I don't the database can't be found. Does django provide some form of utility that lets me run CREATE {DB}? -
Not getting reponse after POST request through axios in react.js
I am creating register and login page in react.js, but after sending post request from axios, I am not able to get back the response, and the .then function does not executes. Also the POST requests works correctly only some of the times(data is added to database). And an error occurs in the backend, during the POST request - Exception occurred during processing of request from ('127.0.0.1', 25074) Traceback (most recent call last): File "c:\python\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\python\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\python\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\MUKUND\.virtualenvs\react-IVhYBaaI\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\MUKUND\.virtualenvs\react-IVhYBaaI\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\python\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine import React, { Component } from 'react'; import axios from "axios"; class Register extends Component { constructor(props) { super(props); this.state = { activeItem: { username:"", email: "", password: "" } }; } handleSubmit = (event) => { alert(this.state.activeItem.email) //console.log("cred = ") //console.log(cred) var data = { username: this.state.activeItem.username, email: this.state.activeItem.email, password: this.state.activeItem.password } axios .post("http://localhost:8000/api/register/", data) .then(res => { alert("registered") console.log("response = ",res) }) … -
Django project problems after upgrading to python 3.8
I developed a Django webapp project using Django 2.2.1 in python 3.7.2 in a pipenv version 2018.11.26 virtual environment in MacBook Air. After an unintentional update to python 3.8 using brew upgrade , there were problems to work on my webapp and launching it. I installed pipenv pip3 install pipenv , and copied and pasted project folder, and used it with an another name, deleted Pipfiles, and ran pipenv install , but there were error: I googled this but found a similar problem but nothing as a solution. Would you please look at these messages and show my correct way to launch my django webapp project? -
How to make inner join on parent field in Django
For data models shown as below, given the product_name, how shall I do a query with Django ORM to get objects containing "distance, city name, price" sorted by distance, price? ### models.py ### class Province(models.Model): name = models.CharField() class City(models.Model): name = models.CharField() distance = models.IntegerField() province = models.ForeignKey(Province) class Price(models.Model): product_name = models.CharField() province = models.ForeignKey(Province) price = models.IntegerField() Same price apply to all cities within a province -
django rest Error: Missing required positional argument in creating objects
I have these serializer classes and I'm trying to create doctor and user together class UserSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = '__all__' extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): print(validated_data) user = User( email=self.validated_data['email'], first_name = self.validated_data['first_name'], last_name=self.validated_data['last_name'], phone_number=self.validated_data['phone_number'], social_id=self.validated_data['social_id'], gender=self.validated_data['gender'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords do not match.'}) user.set_password(password) user.save() return user class DoctorSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Doctor fields = '__all__' def create(self, validated_data): user_data = validated_data.pop('user') print(user_data) user = UserSerializer.create(**user_data) doctor = Doctor( user=user, mc_code=self.validated_data['mc_code'] ) doctor.save() return doctor and I send these json data to these serializers { "user": { "email": "test@test.com", "first_name": "john", "last_name": "doe", "phone_number": "12345678901", "social_id": "1234567890", "password": "password", "password2": "password" }, "mc_code": 123448 } But it gives me this error: Exception Type: TypeError Exception Value: create() got an unexpected keyword argument 'password2' this create() is the create function for UserSerializer I read docs but I couldn't solve the problem. What am I doing wrong? view function just in case @api_view(['POST', ]) @permission_classes(()) def doctor_registration_view(request): if request.method == 'POST': serializer = DoctorSerializer(data=request.data) data = {} if serializer.is_valid(): doctor = serializer.save() else: … -
Django order events by calendar date instead of date posted
I have a newsletter home page that has an events calendar on the side. Sometimes events come up and I need to insert them between two other events. Is there a way I can do this automatically in Django? I know how to order by date posted - for things like blog posts - but I don't see anywhere in the docs how to do this by actual calendar date. This is the code from my view: class HomeView(ListView): model = NewsLetter template_name = 'home.html' def events(self): return Event.objects.all() class PastEventView(ListView): model = PastEvent template_name = 'events.html' ordering = ['event_date'] The past events is alright, but I don't know how to code the order by for the events function under the HomeView class. Any help here would be greatly appreciated. -
how to redirect to a page with pk
i have this function def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/profile') else: form = EditProfileForm(instance=request.user) args = {'form': form} return render(request, 'store/edit_profile.html', args) i want it to redirect to this function def view_profile(request, pk): data = cartData(request) cartItems = data['cartItems'] shippingAddress = ShippingAddress.objects.get(id=pk) # orderItem = OrderItem.objects.get(id=pk) args = {'user': request.user, 'cartItems': cartItems, 'shippingAddress': shippingAddress} # 'orderItem': orderItem return render(request, 'store/profile.html', args) the urls path('profile/<str:pk>/', views.view_profile, name="view_profile"), path('profile/edit', views.edit_profile, name='edit_profile'), i want the first function to redirect to the second but i got 'Page not found' i know the problem with the pk. so i want it to redirect to profile/id. is there a way to solve it? -
How can i write this if statement?
i have some problems with my if statement. {% for user in users %} {% if tournament.tournament_name != user.user_tournament %} {% else %} <p>{{ user.user_first_name }} {{ user.user_last_name }}</p> {% endif %} {% endfor %} class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) tournament_info = models.TextField(max_length=10000) def __str__(self): return self.tournament_name I would like to write something in the form of an entry to a particular tournament where the user after clicking on the "join" button is moved to a sheet where the user is asked to enter their name and choose which tournament they want to join. Is it possible to write a conditional instruction that checks if the name of a given tournament is equal to the name of the tournament that the user has chosen and using it to list the users assigned to the given tournament. -
Django post request looping on same route when using more than 1 replica on Kubernetes cluster
I'm new to kubernetes and was trying to deploy a django app in a shared kubernetes cluster on Kubesail. I was pulling a docker image to run as a container on the cluster. Everything worked as expected until I increased the number of replicas to 2 instead of 1. When I made it 2, my post requests started looping. Meaning, If I'm trying to login into my application, I was again taken back to the login page despite entering the right credentials. Also no user session was created making my app completely inaccessible since all the routes require login. When I made the replicas revert back to 1, everything was normal and app was functioning as expected. Can someone explain why is it so? or can maybe tell what I did wrong?