Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I deal with Django problem if the view function takes long time (about 4~5minutes)?
Hello it's my first time to ask question here. I'm developing websites by Django with some Machine Learning codes. But I faced a problem while designing my view function. Firstly I'll explain about how my websites works. My website page will get input url from user. And with that url our Machine Learning code will return some output data. The problem is my machine learning code needs some time to return output contents, and during that time input url page cannot do any thing without waiting for output contents of Machine learning code. I want to make user free to do anything while machine learning code is working, and how to make this possible? I'm really waiting for your answers. thanks. -
Nginx not serving django 3 through wsgi
I am trying to serve a Django 3 build from nginx through wsgi and I cannot seem to get the last stage. I can browse to the Django site by a runserver and launching the uwsgi.ini, but, when I try to browse to the site through nginx I get a 502 error (bad gateway)(firefox). If I try from a remote site it renders the nginx home page. I have a build of Apache on the same server. I had to spoof an IP and use a unique port to get them running side by side. the nginx/error.log does not register any problem. Below is the uwsgi.ini. [uwsgi] # variables projectname = website base = /opt/website/ # configuration master = true http = :8000 uid = nginx virtualenv = /opt/website/djangoprojectenv pythonpath = %(base) chdir = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.pro #module = %(projectname).wsgi:application module = website.wsgi:application socket = /tmp/%(projectname).new.sock chown-socket = %(uid):nginx chmod-socket = 666 And below is the conf file from nginx/conf.d server { listen 192.168.1.220:81; server_name willdoit.com; access_log off; error_log /var/log/nginx_error.log; location / { uwsgi_pass unix:/tmp/website.sock; include /etc/nginx/uwsgi_params; uwsgi_read_timeout 300s; client_max_body_size 32m; } } The /tmp/website.sock file is owned by nginx:nginx. If there are additional details I need to post, … -
Django-Tables2 with Checkbox Prefilled Value
I am trying to pre-render checked checkboxes using django-tables2 but cannot successfully do so. This is my tables.py file. id is the field I need to store as it's used to update the database, setting the selected field to true on a form submission. How can I get the checked parameter to work with this and properly reference the selected field? class SomeTable(tables.Table): add = tables.CheckBoxColumn(accessor='id',checked='selected') class Meta: model = SomeModel template_name = "django_tables2/bootstrap.html" fields = ['name','add'] Thanks! -
Django - AttributeError: 'NoneType' object has no attribute 'pk'
In short I'm making ToDo app where user can store his todos and projects. Projects consist of todos and can be shared with other users. I'm displaying all todos and projects belonging to a user but when I try to access user todo I get: AttributeError: 'NoneType' object has no attribute 'pk' When accessing todo inside project and even todo inside someone else project everything works fine. Here's log: Traceback (most recent call last): File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\dknapik\.virtualenvs\todo-licencjat-_Vlumx_M\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\dknapik\Documents\Software\Python\lic\todo-licencjat\task\views.py", line 126, in viewtask project = get_object_or_404(Project, pk=task.project_id.pk) Exception Type: AttributeError at /task/4 Exception Value: 'NoneType' object has no attribute 'pk' view: def displayTask(request, task_pk, task): if request.method == 'GET': form = TaskForm(instance=task) return render(request, 'task/viewtask.html', {'task': task, 'form':form}) else: try: form = TaskForm(request.POST, instance=task) form.save() return redirect('currenttasks') except ValueError: return render(request, 'task/viewtask.html', {'task': task, 'form':form, 'error': 'Something went wrong'}) @login_required def viewtask(request, task_pk): task = get_object_or_404(Task, pk=task_pk) project = get_object_or_404(Project, pk=task.project_id.pk) if request.user == task.task_owner: return displayTask(request, task_pk, task) elif task.project_id and project.participant1 == request.user: return displayTask(request, task_pk, task) else: raise Http404 and … -
Django - repeatedly send API call result via websocket on events (REST Framework + Channels)
I came with a problem while integrating Django REST Framework with Django Channels. I have a viewset with retrieve (GET) method that prepares information from several different models in tricky way and sends this "complex" result to the frontend. So when client sends GET request with entity primary key to this endpoint (like /complex_entity/1) he instantly receives everything he needed. And now guys on the frontend side want to have another feature - backend should be able to send results of this complex request to the frontend each time when some of relevant underlying models were changed. Like this: browser subscribes for the changes of ComplexEntity with primary key 1 and when ComplexEntity 1 is changed (or its linked entities which is not a problem) server sends the result of this complex request via websocket. So the request can be executed many times during one websocket connection (on each model change signal). I see two intuitive ways to provide this behaviour: Good(?): somehow execute requests to this viewset retrieve method from the django itself - either by calling this method internally or by executing "loopback" HTTP request. Bad/ugly: copy all complex logic from viewset retrieve method to websocket consumer Also … -
Django model calls an API before save
I have a Django model that needs to call an external API just before saving. The API call is irreversible so I want to call it only before the DB save happens. My code looks something like this: class Model1(models.Model): some_string = models.CharField(max_length=100) class Model2(models.Model): model1 = models.OneToOneField(Model1, on_delete=models.CASCADE) num1 = models.IntegerField() num2 = models.IntegerField() api_output = models.models.JSONField() def save(self, *args, **kwargs): self.api_output = API.call_method(self.num1, self.num2, self.model1.some_string) super().save(*args, **kwargs) Model2 objects can be created from Django Admin but also from the code using Model2.objects.create(). I have 2 questions: When creating an instance of Model2 from Django Admin - if the API call fails (throws an exception) I'd like Django Admin to show a human-readable error instead of the 5xx error page. One way to do that is to have a clean() method but I don't want to call the API before the object is actually saved. Also, when using Model2.objects.create() the clean() method is not called. Is there a way to call the API inside save() and still have Django Admin print a nice error if the call fails? I noticed that during save(), if the OneToOneField constraint is violated (for example trying to create 2 instances of Model2 with … -
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?