Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSL Bad Handshake, Unexpected EOF when communicating with Sentry
I have been having issues integrating Sentry into a Django application. When I run the application locally with Sentry configured in settings.py (imported and initialised with a modern-style DSN) everything works perfectly with all errors showing up on Sentry as expected. However, when running the application on a server it is rare for errors encountered to actually be reported to Sentry, but it does happen occasionally. Looking at the logs for the docker container the application is running in, I can see the following SSL error occasionally appearing shortly after an error is expected to appear on Sentry (although this doesn't happen very often or account for all the times the error doesn't appear on Sentry): Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: SysCallError(-1, 'Unexpected EOF')",),)': /api/<hidden_sentry_id>/store/ This is how I have carried out the Sentry initialisation: sentry_sdk.init( dsn="https://<hidden>@<hidden>.ingest.sentry.io/<hidden>", environment="dev", integrations=[DjangoIntegration()], traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True ) With different settings.py files used depending on the environment. Only the value for "environment" has been changed in the configuration on the server. Does anybody have any advice on how … -
django-tables2 Set Column style when using fields of subclasses
I have two Models: from django.db import models class Model1(models.Model): name = models.CharField(max_length = 200) def status(self): return self.model2_set.first() class Model2(models.Model): fe = models.ForeignKey(Model1, on_delete=models.CASCADE) boolean1 = models.BooleanField() boolean2 = models.BooleanField() string1 = models.CharField(max_length=17) Now I want to have a table get all the information just from the Model1 class and set boolean1 and boolean2 as columns.BooleanColumn. My table class looks like this: class Model1Table(django_tables2.Table): class Meta: model = Model1 template_name = "django_tables2/bootstrap.html" fields = ('name', 'status.boolean1', 'status.boolean2, 'status.string1', ) If field would just contain boolean1 i could set boolean1 = django_tables2.columns.BooleanColumn(null=True). If I do this with status.boolean1 it won't work because status is not defined and therefore has no field boolean1. How can I set the column to a boolean column in this case? -
Django - Store list in one model and set values of list in another model
I'm new to Django and a bit confused to how to go about this... I have two models: variant and item. I want the variant to have a list/JSON/w.e that stores "options" - you can also think of this as modifications to each different variant. E.g. class Variant(models.Model): ... options = ArrayField( ArrayField( models.CharField(max_length=100, blank=True), size=20 ), size=20, null=True ) result: ['mod1', 'mod2'] I now want to grab these options and store a bool/Int/w.e. to declare on or off. However, I'm unsure how to reference the Variant.options as choices or what model to use for my item. -
ModuleNotFoundError in django when adding app
Django can't find my app and it shows me "ModuleNotFoundError" when I try to run server my web this is my setting.py : INSTALLED_APPS = [ ...... 'djmoney', 'transition', --> this is my app ] and this is the complete error : Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.8/dist-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.8/dist-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.8/dist-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'transition' -
Django APPS.PY ignored by Apache2
I have a function in apps.py set to run at Apache boot/restart, however it doesn't and it only works after I pull up the index page. However, if I use Django's development environment it works perfectly. APPS.PY from django.apps import AppConfig class GpioAppConfig(AppConfig): name = 'gpio_app' verbose_name = "My Application" def ready(self): from apscheduler.schedulers.background import BackgroundScheduler from gpio_app.models import Status, ApsScheduler import gpio_app.scheduler as sched import logging logging.basicConfig() logging.getLogger('apscheduler').setLevel(logging.DEBUG) sched.cancel_day_schedule() sched.get_schedule() sched.daily_sched_update() sched.add_status_db() MOD_WSIG 000-default.conf is as follows: <VirtualHost *:80> ServerName 127.0.0.1 ServerAlias localhost ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /robots.txt /path/to/mysite.com/static/robots.txt Alias /favicon.ico /path/to/mysite.com/static/favicon.ico Alias /static /home/pi/poolprojectdir/static <Directory /home/pi/poolprojectdir/static> Require all granted </Directory> <Directory /home/pi/poolprojectdir/poolproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess poolproject python- home=/home/pi/poolprojectdir/venv python-path=/home/pi/poolprojectdir WSGIProcessGroup poolproject WSGIScriptAlias / /home/pi/poolprojectdir/poolproject/wsgi.py Any ideas as to how I get apps.py recognised by Apache2? -
djnago with google smtp [Errno 11001] getaddrinfo failed
in my settings.py EMAIL_HOST = 'smtp.google.com' EMAIL_PORT = 465 EMAIL_HOST_USER = '*********@gmail.com' EMAIL_HOST_PASSWORD = '************' EMAIL_USE_SSL = True in views.py def sendEmail(request, order_id): order = Inventory_Order.objects.get(id=order_id) orderitems = Order_Item.objects.filter(order=order) try: subject = f"Wiss - New Order {order}" to = [f'{order.customer.email}'] from_email = settings.EMAIL_HOST_USER order_information = { 'order':order, 'orderitems':orderitems } message = get_template('Inventory_Management/email.html').render(order_information) msg = EmailMessage(subject, message, to=to, from_email=from_email) msg.content_subtype = 'html' msg.send(fail_silently=False) print(f'message sent to {order.customer.email}!') except IOError as e: print('Failed') print(e) return e when i call the function i get the following error [Errno 11001] getaddrinfo failed, What's The Problem? Any Help is Appreciated... -
Queryset of model instances based on related model
I've got two models. class Color(models.Model): name = models.CharField(max_length=120, null=True, blank=True) class Car(models.Model): user = models.ForeignKey(Color, on_delete=models.CASCADE, default=None) price = models.DecimalField(max_digits=10, decimal_places=2) How can I get a queryset of Color instances where the Car instances that are related to those Color instances have a price > 1000? Thanks! -
Can't give css class to django error message
I'm trying to format my Django error messages with some css, but i just can't seem to apply it. (The CSS file is added correctly I applied other classes from it, those work just fine). The strange thing about it is that if i try to apply a class from bootstrap like "alert-danger" that works just fine Here's my html code: {% for field in form %} <div class="asd">{{ field.errors}}</p> {% endfor %} And the css as well .asd{ font-size: 1rem; margin-left: 20px; } -
regex query does not work with django-MYSQL
on development I use the default sqlite and I have no issues. this is how I build the query: def similar_names_filter(queryset: QuerySet, name_field: str, name_value: str): filter_key = name_field+"__regex" filter_value = r"{}(?: \([0-9]+\))?".format(name_value) return queryset.filter(**{filter_key: filter_value}).values_list(name_field, flat=True) but on production where we use mysql it does not work and produces the following message: (1139, "Got error 'repetition-operator operand invalid' from regexp") What am I missing? Thanks in advance -
Elasticsearch with Django: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError
I try to itergrate elasticsearch in django project. But when I execute command python manage.py search_index --rebuild it made this error elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fde186b2b50>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fde186b2b50>: Failed to establish a new connection: [Errno 111] Connection refused) After run docker-compose, I can access to elasticsearch http://localhost:9200 via chrome. This is setting.py file: INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_elasticsearch_dsl', ] ELASTICSEARCH_DSL={ 'default': { 'hosts': 'localhost:9200' }, } And document.py file: from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Question @registry.register_document class QuestionDocument(Document): class Index: #name of elasticsearch index name = 'questions' setting = { 'number_of_shard' : 1, 'number_of_replicas' : 0} class Django: model = Question fields = [ 'question_text', 'pub_date', ] How can I resolve it? -
How to get data related from another table django rest framework
I have three model Pesticide, Disease and Instruction what i want is to get all disease with relation to pesticide which relate to instruction model class Disease(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Pesticide(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Treatment(models.Model): disease = models.ForeignKey(Disease, related_name='treatments', on_delete=models.DO_NOTHING) pesticide = models.ForeignKey(Pesticide, related_name='treatments', on_delete=models.DO_NOTHING) def __str__(self): return self.instruction and serializer class PesticideSerializer(serializers.ModelSerializer): class Meta: model = Pesticide fields = ('id', 'name') class DiseaseSerializer(serializers.ModelSerializer): pesticides = PesticideSerializer(source='treatment_set', read_only=True) class Meta: model = Disease fields = [ 'id', 'name', 'pesticides', ] My problem is that i can not get pesticides in django serializer -
Why my swipper 3d slider is not working properly when I make a for loop in Django?
{% extends 'elections/base.html'%} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"> <div class="row candidate_details"> {% for president in presidents %} <div class="card"> {% if forloop.counter == 1 %} <div class="card-body"> <img src="{{president.imageURL}}" alt="profile image" class="profile-img1"> <h1>{{president.first_name}} {{president.last_name}}</h1> </div> </div> {% else %} {% endif %} <div class="card"> <div class="card-body"> <h1>Incoming Results</h1> <hr> <h2>Total Votes</h2> <h1>1,233,333 votes</h1> <hr> <h1>36%</h1> <hr> </div> </div> {% endfor %} </div> </div> </div> </div> </div> </div> </div> <script src="https://unpkg.com/swiper/swiper-bundle.js"></script> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script> <script> var swiper = new Swiper('.swiper-container', { effect: 'coverflow', grabCursor: true, centeredSlides: true, slidesPerView: 'auto', coverflowEffect: { rotate: 30, stretch: 0, depth: 500, modifier: 1, slideShadows: true, }, pagination: { el: '.swiper-pagination', }, }); </script> {% endblock content %} I want to have a 3d slider of images and data in the description area. I want to display the image of a candidate and his details for each candidate one at time on each slide as shown in this image: -
Easy-thumbnails/Django Rest Framework : InvalidImageFormatError with Django File
I am using Django Rest Framework to upload profile picture and easy-thumbnails to resize my images. I test my API and I have this result : File "/home/worldorama/profile/views.py", line 84, in post profile_picture = services.upload_profile_picture( File "/home/worldorama/profile/services.py", line 225, in upload_profile_picture return ProfilePicture.objects.create( File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 740, in save self.save_base(using=using, force_insert=force_insert, File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 777, in save_base updated = self._save_table( File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 907, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1374, in execute_sql for sql, params in self.as_sql(): File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1316, in as_sql value_rows = [ File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1317, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1317, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1268, in pre_save_val return field.pre_save(obj, add=True) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/files.py", line 288, in pre_save file.save(file.name, file.file, save=False) File "/usr/local/lib/python3.8/site-packages/easy_thumbnails/files.py", line 759, in save content = Thumbnailer(content, name).generate_thumbnail(options) File "/usr/local/lib/python3.8/site-packages/easy_thumbnails/files.py", line 385, in generate_thumbnail raise … -
Tests not running - Postgres database not connect via circle ci
I am running a Django project and I have set up tests and wanted to run them through circle ci. However, when I push my code to GitHub. Circle CI can't seem to connect the database. This only started when I introduced a .env file and python decouple What is the best way to setup environment variables that I need for development and the same time for Circle CI? I have tried creating seperate settings config files. I have tried creating environment variables on the CircleCI dashboard but Circle CI is still not able to connect to the db and it seems like the environment variables are causing the error but I am not sure why? To see the error. Click here:https://i.stack.imgur.com/swVfK.png. You can also clone my project from github to test it out yourself and also to check out my config.yml Github Repo I would really appreciate some insight on this -
MultipleObjectsReturned at /account/ get() returned more than one Order -- it returned 2
i want to show the ordered product in the account.html as user account views but it only show one product and when item increase from more then one product then shows that error , when i change the get to filter it iterates through models but don't show the detail through that views.py class AccountView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=True) # when change get from filter it don't show the product name and details context = { 'object': order } return render(self.request, 'account.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have any order yet") return redirect("/") when change the object.items.all to object it don't show detail but it iterates through and print the exact number of times as the product ordered account.html {% for order_item in object.items.all %} <tr> <td data-th="Product"> <div class="row"> <div class="col-sm-2 hidden-xs"><img src="{{ order_item.item.image.url }}" alt="..." class="img-responsive"/></div> <div class="col-sm-10"> <h4 class="nomargin">{{ order_item.item.title }}</h4> <p>Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet.</p> </div> </div> </td> <td data-th="Price">{{ order_item.item.price }}</td> <td data-th="Quantity"> <input type="number" class="form-control text-center" onclick="update_item()" value="{{ order_item.quantity }}"> </td> <td data-th="Subtotal" class="text-center"> {% if order_item.item.discount_price %} &#8377;{{ order_item.get_total_discount_item_price }} <span … -
Django Image input failed, image cant save to static file
I try to allow user to upload some image using django model form, but that images cant store to my database. Went i am try to print that query that all show it but doesnt store in database Here is the code # views.py def add_thumbnails(request): if request.user.is_authenticated: if request.method == 'POST': form = PoolForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('home:index')) else: form = PoolForm() return render(request, 'home/add_thumnails.html', { 'form' : form, } ) else: return HttpResponseRedirect(reverse('home:login_status')) # models.py class Pool(models.Model): date_add = models.DateTimeField(auto_now=True) title = models.CharField(max_length=30) categories = models.ForeignKey(Categories, on_delete=models.CASCADE) status = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) img_1 = models.ImageField(upload_to='static/upload_tumb/') img_2 = models.ImageField(upload_to='static/upload_tumb/') vote_img1 = models.IntegerField(default=0) vote_img2 = models.IntegerField(default=0) def __str__(self): return self.title # forms.py class PoolForm(forms.ModelForm): img_1 = forms.ImageField(label='Image 1') img_2 = forms.ImageField(label='Image 2') class Meta: model = Pool fields = ( 'title', 'categories', 'img_1', 'img_2', ) -
Reuse queryset in multiple views
I am building a application which has several views - HomePageView, SearchPageView and DetailPageView. The aforementioned views return the same queryset. My question is, what is the proper way to define let's say a "global" queryset which would be then used in multiple Views. To illustrate my point here is an example of what I have: class HomePageView(TemplateView): def get_queryset(): return Systemevents.objects.filter(**filter) class SearchPageView(ListView): def get_queryset(): return Systemevents.objects.filter(**filter) class LogDetailView(DetailView): def get_queryset(): return Systemevents.objects.filter(**filter) What I would like to achieve: global queryset = Systemevents.objects.filter(**filter) class HomePageView(TemplateView): def get_queryset(): return queryset class SearchPageView(ListView): def get_queryset(): return queryset class LogDetailView(DetailView): def get_queryset(): return queryset Thanks in advance, Jordan -
Django - no migrations folder after refactoring projects and apps names
I have refactored my app and project names, but after that Django doesn't create migrations folder in my app and doesn't actually apply my models migrations. Even after migrations (with no warning nor error) I have no tables with my objects. Does anybody know how to force django to do those migrations? -
How to call aggregate function in html using django
How to remove unnecessary words just like this {'amount__sum': 480.0} in my html ? i just want to print the value only. this is my html <span>{{total}}</span> this is my views.py ..... total = CustomerPurchaseOrderDetail.objects.filter( id=itemID ).aggregate( total=Sum( F('unitprice') * quantity, output_field=FloatField(), ) )['total'] return render(request, "cart.html", {"total":total}) -
Django Channels - Channel Layer?
I am newbie in web development and learning mostly Django and Vanilla Javascript, CSS for now. I got confused while reading the docs about Django Channels. In tutorials it is written that Channel Layer is like kind of a router which passes HTTP request to views and Websocket traffic to Consumers and Redis is mostly used for Channel layer. As I mentioned I am kind of newbie in development and never used Redis. The thing I understood from reading couple of posts that Redis is used as cache for lowering the load on database accesses. So my question is: What is relattion of Channel Layer and Redis. If Redis is a caching technology, how it is used as router for requests? -
Selecting framework for python language with matplotlib, numpy, scipy, soundfile, sounddevice
I am trying to develop web application using python technology but searching for suitable framework. I am not sure how much django, streamlit or flask will be suitable due to its limitations. Framework should be compatible with below mentioned libraries. matplotlb, numpy, scipy, soundfile and sounddevice. Also is it possible to plot graph using matplotlib in real time on website? Please refer the following image. Please suggest supportive framework so that it won’t be a problem going forward to develop web app.Real time plotting of signal -
how django compress render , it watest time in html transport? [closed]
my django server website loads many time in content download enter image description here enter image description here my django codes is def function(request): data_list = get_data_list() #big data return render(request, 'xx.html',{'data_list':data_list}) -
Django Authentication using external Http request (http://x.x.x.x:8013/api/LDAP/LoginLDAP ) in windows 10
I have a simple Django application that is currently running on normal basic auth in Django. I need to integrate with below given external API which accepts username and password, this is provided by my organization so that all employees in the organization can access the app with their org username and password. http://x.x.x.x:port/api/LDAP/LoginLDAP { "username": "userid", "password": "password" } should be sent as JSON and use the POST method if user exists this returns me his details { "username": "userid", "email": "password", "role" : "role", } if user does not exist or auth details are wrong it returns { invalid credentials } can anyone help me with what kind of auth should I use? Thanks in advance. -
Celery failing with ValueError on Python 3.8
I upgraded my environment to python 3.8 and now my celery (tried v4.4.2 to 4.4.7) is not able to start with the following error: ValueError: invalid width -2 (must be > 0) Any ideas how I can solve this? Thanks! -
why signup form is not submitting in database ? Need advice
After fillup signup form it only shows html waning shows up(please fill this field) in the middle of the signup form and when click on the button of signup withour fill up form, same html warning shows up (please fill this field) in the middle of the signup form instead of every input field. why signup form is not submitting in the database. urls.py (connect main folder) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('account.urls')), ] urls.py (account app folder) from django.urls import path, include from account import views from django.contrib import admin urlpatterns = [ path('', views.account, name='account'), path('signup', views.signup, name='signup'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), ] views.py (account) from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User, auth from django.contrib.auth import authenticate, login, logout # Create your views here. def account(request): return render(request, 'account/base.html') def signup(request): if request.method == "POST": # get the post parameters first_name = request.POST['fname'] last_name = request.POST['lname'] email = request.POST['email'] username = request.POST['username'] password1 = request.POST['pass1'] password2 = request.POST['pass2'] # create the user user = User.objects.create_user(username=username, password=password1, email=email, first_name=fname, last_name=lname); user.save() return redirect('account') def login(request): return HttpResponse('hello') def logout(request): return HttpResponse('hello') base.html <!doctype html> {% …