Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django nginx upstream prematurely closed connection while uploading large data
I am getting this error: upstream prematurely closed connection while reading response header from upstream when I try to upload large data from an excel file to the server. I tried with only 10000 inputs with 4 rows each. It doesn't do this when I try it on my localhost, so this might be the remote server's config. This is what I currently have in my nginx.conf file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; client_max_body_size 20M; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } I added the client_max_body_size 20M; line and restarted nginx but it was the same. -
Django with Heroku doesn't server static files except admin files
I'm trying to deploy my project to heroku. Everything is working, but without static files. I get such exception form browser: artyom-blog-v2.herokuapp.com/:1 Refused to apply style from 'https://artyom-blog-v2.herokuapp.com/static/bootstrap/dist/css/bootstrap.min.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. artyom-blog-v2.herokuapp.com/:9 GET https://artyom-blog-v2.herokuapp.com/static/jquery/dist/jquery.min.js net::ERR_ABORTED 404 (Not Found) artyom-blog-v2.herokuapp.com/:10 GET https://artyom-blog-v2.herokuapp.com/static/bootstrap/dist/js/bootstrap.min.js net::ERR_ABORTED 404 (Not Found) Code: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = '/static/' STATIC_DIR = BASE_DIR / 'posts' / 'static' STATICFILES_DIRS = [STATIC_DIR] # NEED STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' How to solve it? -
Simple python object has no attribute and cannot set queryset as variable
I'm new to python and django and am receiving the following attribute error: AttributeError at /account/1/ 'Account' object has no attribute 'subscribers_set' I don't know why this happens because one account can have many subscribers. In the shell I can run a query for an account that will return all the subscriber objects, e.g. account.subscriber_set.all() returns <QuerySet [<Subscriber: bob@bob.com>, <Subscriber: sally@salhurst.com>, <Subscriber: jessy123@something.com>]> - but for some reason I can't set the queryset to a variable: trying to set variable with subscribers = account.subscribers_set.all() returns error AttributeError: 'Account' object has no attribute 'subscribers_set' In my views.py I have this account function: def account(request, id): account = Account.objects.get(id=id) subscribers = account.subscribers_set.all() # error here? context = {'account': account, 'subscribers': subscribers} return render(request, 'accounts/account.html', context) And my view: {% extends 'accounts/main.html' %} {% block content %} <h1>Account Page for {{account}}</h1> <p>Email Address: {{account.email}}</p> {% for sub in subscribers %} <p>{{subscriber}}</p> {% endfor %} {% endblock %} And url.py: urlpatterns = [ path('account/<str:id>/', views.account, name="account"), ] The class model is basically just the user model: class Account(AbstractUser): pass And there's a one:many relationship between Accounts and Subscribers: class Subscriber(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True) date_joined = … -
Django intermediary model
I dont understand Django Intermediary models at all. Let's say that i want to add one more additional field to User model, and store relationship between two users in another model(intermediary) like this: class Contact(models.Model): user_from = models.ForeignKey(User...) user_to = models.ForeignKey(User...) ... And the field i want to add is: following = models.ManyToManyField('self', through=Contact, related_name='followers', symetrical=False) What really happen when i call user_object.followers.all() and what is the difference between user_object.following.all() are they both the same? -
Django error with template print variables
Why is Django returning <django.contrib.messages.storage.fallback.FallbackStorage object at 0x000002503DA6F188> when I tried to print a variable in the template -
HTML/Django - Carousel with one picture active and the before and after translucent
I was not sure how to word my question, and I really don't have any example code to show because I have tried 100 different searches and can't seem to get it to work... I am using Django to create a website and the designer specified that I need to have a section like below: The image It looks like it would be a carousel with the active picture in the middle, and one inactive picture on each side and translucent. The arrows are on either side and not below. I am hoping I was clear enough and this is a somewhat simple solution. Thank you for you help in advanced! -
python telegram bot to get next question I need to type anything
I'm working with Django and Python Telegram Bot, the problem that I have is that when the conversation starts and I get to my 3rd question and answer, I need to type anything again in order to get the next question As you can see in the picture if I dont type 'OK' I do not get the next question. This is my code GET_CLIENTE, GET_TELEFONO, SET_MENU, SET_TELEFONO, SET_CLIENTE, SET_NOMBRE, SET_EMAIL, GET_EMAIL, RESPUESTAS = range( 9) def cliente(update: Update, _: CallbackContext): nombre = Cliente.objects.filter(id=1)[0] nombre = str(nombre) update.message.reply_markdown_v2( nombre, reply_markup=ForceReply(selective=True), ) def set_nombre(bot, update): message = 'Dame el nombre completo de la persona' pass def start(update: Update, _: CallbackContext) -> None: """Send a message when the command /start is issued.""" keyboard = [['Clientes', 'Reporte']] message = 'Selecciona la Opción deseada' reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True) update.message.reply_text(message, reply_markup=reply_markup) return SET_MENU def set_menu(update: Update, _: CallbackContext) -> None: """ Set option selected from menu. """ keyboard = [['Alta', 'Actualizar']] message = 'Qué vamos a hacer' reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True, resize_keyboard=True) update.message.reply_text(message, reply_markup=reply_markup) return SET_CLIENTE def set_cliente(update: Update, _: CallbackContext) -> None: message = 'Dame el nombre completo de la persona' update.message.reply_text(message) return GET_CLIENTE def get_nombre(update: Update, context: CallbackContext) -> None: nombre = … -
get dict value from prefect_related data without creating nested lists
I'm getting values from multiple models using the snippet below: a = App1.objects.all().prefetch_related("app2", "app3").filter(id=self.id) and getting results like this app_1 = [x.app2.values() for x in a] this result creates [<QuerySet [{'field1': value1, 'field2': value2,......}]>] It seems unnecessary (perhaps I am overcomplicating the process) to create a list of list of dict just to get values app1 Is there a way to get the inner dict without having to reference something like print(app_1[0][0].get("field1")) -
Escaping quotes in django template within javascript
I'm having trouble figuring out how to handle the quotes in the following: var attributes = { Description: "<a href="{% url 'project_map' project.id %}">{% url 'project_map' project.id %}</a>" } The link text will render as expected but the href resolves to a blank. I've tried escaping the quotes and other attempts to shift things around with no joy. This is django tempting language mixed with javascript. -
Setting up Django AnonymousUser logins with djangorestframework-simplejwt web tokens
I'm using djangorestframework-simplejwt to handle authentication on a project I'm working on using refresh and access tokens. I'd like to implement a way for users to use my note-taking app without making accounts. I was thinking of using Django's AnonymousUser object for this. The problem is I can't find anything online that describes how to do this with JSON web tokens. I tried logging in by sending in null and empty strings for the username and password, but my backend gave me a response of 400 BAD REQUEST. What should I add to my backend to allow users to click on a link and receive refresh/access tokens as AnonymousUser? authentication/serializers.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from .models import ErsatzNoteUser class ErsatzNoteUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) password = serializers.CharField(min_length=8, write_only=True) class Meta: model = ErsatzNoteUser extra_kwargs = { 'password': { 'write_only': True } } fields = [ 'email', 'password' ] def create(self, validated_data): password = validated_data['password'] instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class ErsatzNoteTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super(ErsatzNoteTokenObtainPairSerializer, cls).get_token(user) token['user'] = user.email return token authentication/views.py from rest_framework import status, permissions from rest_framework.exceptions import AuthenticationFailed from rest_framework.response import Response from rest_framework.views … -
Posting comments with django-comments-xtd returns SQL syntax error
I'm trying to implement django-comments-xtd on my blog for the first time. Almost everything seems to be well, except that I'm getting this error when posting (authenticated user) or confirming (anonymous user) comments: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY django_comments_xtd_xtdcomment.thread_id ASC, `django_comments_x...' at line 1") Any advice on how to resolve it? I'm using MySQL 8.0, but I've also tested with 5.6 and still get the same error. -
Can I use a Paypal and 2Checkout payment integration in Pakistan to take transections from around the globe? (even Paypal is not allowed here)
I live in Pakistan. I just made a Django E-Commerce Website and wanna set a payment integration of Paypal (Paypal is not available for transections) to take money transections from other countries. -
Downloading Python Packages onto Bitnami through AWS Lightsail
I am trying to publish a Django project through AWS LightSail however, I am unable to get the dependencies necessary to run my manage.py file. I try the following command: pip3 install "packagename" Defaulting to user installation because normal site-packages is not writeable I've also tried easy_install "packagenmae" which just stalls as it looks for the package. How can I go about installing my requirements.txt files. Thank you for all your help! -
Websocket immediately disconnects after upgrading Heroku Redis version for Django Channels app
Since Heroku will deprecate the version of Redis my app was using (5.0.12), I upgraded to Redis version 6.2.3. Since then, the websocket immediately triggers the onclose callback in my client. In the logs, I get this error message: 2021-06-21T18:18:20.761857+00:00 app[web.1]: 2021-06-21 18:18:20,761 ERROR [daphne.server] [asyncioreactor.py:290] - Exception inside application: [Errno 104] Connection reset by peer 2021-06-21T18:18:20.761866+00:00 app[web.1]: Traceback (most recent call last): 2021-06-21T18:18:20.761867+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/sessions.py", line 183, in __call__ 2021-06-21T18:18:20.761867+00:00 app[web.1]: return await self.inner(receive, self.send) 2021-06-21T18:18:20.761868+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/middleware.py", line 41, in coroutine_call 2021-06-21T18:18:20.761868+00:00 app[web.1]: await inner_instance(receive, send) 2021-06-21T18:18:20.761868+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/consumer.py", line 59, in __call__ 2021-06-21T18:18:20.761869+00:00 app[web.1]: [receive, self.channel_receive], self.dispatch 2021-06-21T18:18:20.761869+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/utils.py", line 58, in await_many_dispatch 2021-06-21T18:18:20.761870+00:00 app[web.1]: await task 2021-06-21T18:18:20.761870+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels/utils.py", line 50, in await_many_dispatch 2021-06-21T18:18:20.761871+00:00 app[web.1]: result = task.result() 2021-06-21T18:18:20.761871+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 435, in receive 2021-06-21T18:18:20.761871+00:00 app[web.1]: real_channel 2021-06-21T18:18:20.761872+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 490, in receive_single 2021-06-21T18:18:20.761872+00:00 app[web.1]: index, channel_key, timeout=self.brpop_timeout 2021-06-21T18:18:20.761872+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 330, in _brpop_with_clean 2021-06-21T18:18:20.761873+00:00 app[web.1]: async with self.connection(index) as connection: 2021-06-21T18:18:20.761873+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 835, in __aenter__ 2021-06-21T18:18:20.761873+00:00 app[web.1]: self.conn = await self.pool.pop() 2021-06-21T18:18:20.761873+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/channels_redis/core.py", line 73, in pop 2021-06-21T18:18:20.761874+00:00 app[web.1]: conns.append(await aioredis.create_redis(**self.host, loop=loop)) 2021-06-21T18:18:20.761886+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/aioredis/commands/__init__.py", line 175, … -
Change Django HyperlinkedModelSerializer ID
I'm learning about Django Rest Framework and trying to get used to it. I'm using a HyperlinkedModelSerializer which, if I understand correctly, allows me to call my models by id like www.example.com/api/1. I was wondering if there was any way to change the id to a custom field, like a username - e.g. www.example.com/api/myusername (similarly to how GitHub API works). models.py from django.db import models class RoomInfo(models.Model): name = models.CharField(max_length=50) dev_name = models.CharField(max_length=50) brief_desc = models.TextField() def __str__(self): return self.name serialisers.py from rest_framework import serializers from .models import RoomInfo class RoomInfoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RoomInfo fields = ['id', 'name', 'dev_name', 'brief_desc'] views.py from django.shortcuts import render from rest_framework import viewsets from rest_framework.generics import RetrieveAPIView from .models import RoomInfo from .serializers import RoomInfoSerializer class RoomApi(viewsets.ModelViewSet): queryset = RoomInfo.objects.all().order_by('name') serializer_class = RoomInfoSerializer -
Unable to register django custom template tags
I want to register 3 custom template tags and show the info they generate in all the pages of my project. I have read the documentation and created the following files: blog_tags.py from django import template from django.db.models import Count from ..models import Post register = template.Library() @register.simple_tag def total_posts(): return Post.published.count() @register.inclusion_tag("blog/post/latest_posts.html") def show_latest_posts(count=5): latest_posts = Post.published.order_by("-publish")[:count] return {"latest_posts": latest_posts} @register.simple_tag def get_most_commented_posts(count=5): return Post.published.annotate(total_comments=Count("comments")).order_by( "-total_comments" )[:count] And my template: base.html {% load static %} {% load blog_tags %} <!DOCTYPE html> <html> <head> <title> {% block title %}{% endblock %} </title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %}{% endblock %} </div> <div id="sidebar"> <h2> My blog</h2> <p> This is my blog. I've written {% total_posts %} posts so far.</p> <h3> Latest posts</h3> {% show_latest_posts 3 %} <h3> Most commented posts</h3> {% get_most_commented_posts as most_commented_posts %} <ul> {% for post in most_commented_posts %} <li> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </li> {% endfor %} </ul> </div> </body> </html> However, the tags are not getting loaded. The page does not open. Instead, I get the following error: Invalid block tag on line 3: 'total_posts'. Did you forget to register or load this … -
Django don't display default value in form field
I have a large django form where most of the options have the same default value. When a user goes to enter the form they have to remove the default value before they can enter their information. I figured I could solve the issue by adding a place holder widgets = { 'form_item': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'OEM'}) } Now when I load the form it still has the default value text entered but if you remove it the place holder text is showen. How do I not display the default value text in a form field -
Django Authentication with pyrebase
I know in Django there is a check authentication by: if request.user.is_authenticated: And there is a decorator like: @login_required I can't use them because I work with realtime database of firebase, so I want to know how to replace them in django while working with pyrebase. -
DRF Create a custom relational data or smth similar?
I have three mudles, one called Events and one called Tasks. Each one have field called deadline. Goal: I need create a section in my Custum User modle called Todis and asection called Overdos where i filter the Events and tasks tha has deadline less than now and put the in the todos and i need to filter the other Tasks and Events object to put them in theOverdows. I know how to filter and all these stuff but I nedd an idea to get that data and set them inside the user modle without create a new datafield to gether them, just like using the relational data -
Django signals how to create register forms for two types of users with groups
I have two types of users all inheriting from the User model. Class 'Teacher' and class 'Student' each with its own registration form and belonging to the respective groups 'teacher' and 'student'. but when I try to register a user 'Teacher', he registers in the group 'prof' and 'etudiant' at the same time and i have a duplicate integrity error. How can i avoid this ? models.py : this is my two models models.py signals.py : signals.py views.py : pofesseur register register view views.py : etudiant register register view apps.py : ready function django admin panel : my two groups concerned groups in admin panel Sorry for my aproximative english -
How to loop through visible form fields but do something when a certain field is met in Django?
Is it possible to stop at a certain form field when you looping through the visible form fields in form's __init__? def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): if visible == "field_name": #<---? #do something -
How can I bypass drf Token Authentication when using firebase for authentication in django?
I need to sign in a user using firebase from my django app.I have done what I think I needed to do but I seem to be missing something.I am using the pyrebase library.I have created a user on firebase and now I need to sign them in. I am posting the email and password on Postman and I get the 'idToken' and 'refreshToken', which means the user gets authenticated on firebase.But this only works when I use the drf Token authentication(DEFAULT AUTH CLASSES) and authorization token of a user previously created on django admin. What am I missing so that I can authenticate the user without the drf token authentication? views.py config = { "apiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxx", "authDomain": "xxxxx.firebaseapp.com", "databaseURL": "https://xxxxxxxxx-default-rtdb.firebaseio.com", "storageBucket": "xxxxxxxxx.appspot.com", } firebase = pyrebase.initialize_app(config) auth = firebase.auth() class Auth(APIView): def post(self, request, format=None): email = "xxxx@gmail.com" password = "xxxx" user = auth.sign_in_with_email_and_password(email, password) return Response(user) Settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.TokenAuthentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), } -
Can You Add More Details to my Temperature Heat Control App?
Hello i am building a temperature heat monitor using arduino. This is the pseudo code LED1 LED2 LED3 LEDRED Relay1 Relay2 When Settings are changed If device is at 0% Power (0W) LED1, LED2, and LED3 are off If device is at 0 to 39% power (2.5 W) LED 1 is on, LED2 and LED3 are off If device is at 40 to 79% power (5 W) LED 1 and LED2 are on, LED3 is off If device is at 80 to 100% power (7.5 W) LED 1, LED2 and LED3 are on Ton = Tcycle * Intensity / 100% Continuously happen with timing signals If Tsurface >Tmax Relay1, Relay2 are off LEDRED is on Else At t=0+Ton/2 Turn Relay1 off At t=Tcycle-Ton/2 Turn Relay 1 on At t=Tcycle/2 - Ton/2 Turn Relay 2 on At t=Tcycle/2 + Ton/2 Turn Relay 2 off So far this is what i have done from django.contrib import admin from django.urls import path, include from .views import (home,led_off,led_on, increase_temp,decrease_temp) urlpatterns = [ path('', home, name='home'), path('on/', led_on, name='led_on'), path('off/', led_off, name='led_off'), path('inc/', increase_temp, name='inc'), path('dec/', decrease_temp, name="dec"); from view.py from django.conf import settings from pyfirmata import Arduino import warnings # Arduino configuration try: board … -
STATICFILES_DIRS pointing to remote server without being collected
I have a view that is loading a table of elements from an SQL server database to show a list of invoices from system. these invoices files are located in a shared network drive. right now in my development environment I'm able to do a runserver and use my website as I want. The proble comes when I deploy in a IIS Server (production) since I need to now provide these files from the same remote serve and I have the problem that my staticfiles_dirs is not being resolved. Right now I have: STATIC_URL = '/static/' STATICFILES_DIRS = ['//SharedDrive/folder/folder',] and my home.html is doing a {%load static%} where later I reference the path using {% static %} the problem is that this works in my local machine, but not deployed. how can I make it work without having to move this content to my django server? (since the data is over 400gb) Thank you. -
How to test views in Django?
I try to create test to my views in django app, in my setUp method i want to create new object and then pass id of this object to reverse('edit') to test passing an id like I have in my urls, here is code: test_views.py def setUp(self): self.client = Client() self.edit = reverse('edit', args=['id']) self.id = Employee.objects.create( econtact='testContact', eemail='test@tset.pl', ename='testName' ).id urls urlpatterns = [ path('edit/<int:id>', views.edit, name="edit"), ] model class Employee(models.Model): ename = models.CharField(max_length=100) eemail = models.EmailField() econtact = models.CharField(max_length=15) can somone tell me why, after run this test case, my console throw me: django.urls.exceptions.NoReverseMatch: Reverse for 'edit' with arguments '('id',)' not found. 1 pattern(s) tried: ['edit/(?P<id>[0-9]+)$'] thanks for any help!