Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to activate virtual envirooment for existing django project using pipenv in 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: ✘ Locking Failed! ERROR:pip.subprocessor:Command errored out with exit status 1: .... .... After several hours of trial and error, I found the problem is with the version of some packages in my requirements.txt. I have these packages in my project: backports.csv==1.0.7 certifi==2019.3.9 chardet==3.0.4 defusedxml==0.6.0 diff-match-patch==20181111 Django==2.2.1 django-allauth==0.39.1 django-ckeditor==5.6.1 django-crispy-forms==1.7.2 django-finalware==1.0.0 django-import-export==1.2.0 django-js-asset==1.2.2 django-recaptcha==2.0.5 et-xmlfile==1.0.1 gunicorn==19.9.0 html5lib==1.0.1 idna==2.8 jdcal==1.4 numpy==1.16.3 oauthlib==3.0.1 odfpy==1.4.0 openpyxl==2.6.1 pandas==0.24.1 Pillow==5.4.1 psycopg2==2.7.7 psycopg2-binary==2.7.7 pycparser==2.19 pyparsing==2.3.1 PyPDF2==1.26.0 Pyphen==0.9.5 python-dateutil==2.8.0 python3-openid==3.1.0 pytz==2019.1 PyYAML==3.13 reportlab==3.5.21 requests==2.21.0 requests-oauthlib==1.2.0 six==1.12.0 sqlparse==0.3.0 tablib==0.13.0 urllib3==1.24.3 webencodings==0.5.1 whitenoise==4.1.2 xhtml2pdf==0.2.3 xlrd==1.2.0 xlwt==1.3.0 The first problem was for pandas 0.24.1, and I removed its version number, then pipenv succeeded to lock but it failed to install two other packages Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Building requirements... Resolving dependencies... ✔ Success! … -
How to limit add to a model in django
How to limit add to a model in django ? i would like to create only one company on this model, only one, so if user want to add more, it s not possible. class Company(models.Model): name = models.CharField(max_length=64) address = models.TextField(max_length=250) -
How to manage python file from views.py
I am collecting data from a form. How can I pass data to a python file containing an infinite loop from views.py? How can I run this file from views.py? How can I stop this file from views.py? If I want to run many similar files(inf.py) at the same time, should I create them in a separate folder / application? Something like this : views.py: def index(request): if request.method == "POST": genform=Gen_info_form(request.POST) if genform.is_valid(): geninfomodel = GeneralInfo() geninfomodel.email = genform.cleaned_data["email"] geninfomodel.password = genform.cleaned_data["password"] geninfomodel.name = genform.cleaned_data["name"] geninfomodel.X= genform.cleaned_data["X"] geninfomodel.Y= genform.cleaned_data["Y"] geninfomodel.Z= genform.cleaned_data["Z"] geninfomodel.save() #send X, Y, Z to inf.py and execute it time.sleep(36000) #stop inf.py return HttpResponseRedirect("/") inf.py: X=#get value for variable X Y=#get value for variable Y Z=#get value for variable Z while True: X=X+Y X=X*Z -
django formset: "add" button creates form but dont display it
I have a formset rendered in template and everything works. there is only one (big) problem. When clicking on "add" button, a form gets created but does not show up. Therefore, when the user click on the "save" button to save the formset, then the second form appears with django error messages about submitting null values. I don't understand what is wrong about my code causing this issue and I have been banging my head on the wall for a while so i attach it here, hoping that someone could see where I am messing up <section class="no-padding-top no-padding-bottom"> <div class="container-fluid"> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h1 class="h3 mb-0 text-gray-800">{% trans 'RECORD NEW SALE' %}</h1> </div> <form method="POST" class="form-validate" id="formset"> {% csrf_token %} {{ formset.management_form }} <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} … -
Is it possible to download Django ORM somewhere?
I really like how easy it is to create a database (models) in Django. But I do not need Django, I need a base (or ORM) to work with a very simple script (one .PY file). Can I download Django ORM? If not, is there any very similar ORM for Python? I would hate to write SQL code by hand. -
Can't get page_published signal
Following the docs found here but I'm not receiving the signal. Is there more to add? community/signals.py from wagtail.core.signals import page_published from wagtailPages.models import CommunityArticle from notification.models import Notification def notify_article_author(sender, **kwargs): print("Processing page_published signal") ... page_published.connect(notify_article_author, sender=CommunityArticle) -
No simple solution for Django multiple select field . It is Django limitation
It is really sorry that Django still can not use multiple select fields.Anyone can provide a simple solution. A simple form which will capable to take name, address and multiple select choice fields to be saved . -
Create variable in Django template
I have this in my template: {% for category in menu_categories %} {% with menu_button = "menu_"{{category}} %} <button class="button {{menu_button}}" onclick="showItem(menu_button)">{{category}}</button> {% endwith %} {% endfor %} I am trying to create a series of buttons with class name by iterating a queryset of model categories. I create a variable menu_button so that I could systematically name them, and pass the name to a JavaScript function showItem(). But I get the error 'with' expected at least one variable assignment. What am I doing wrong? Thanks. -
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?