Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django) Creating a simple website with account signup/login WITHOUT using the basic Django auth/admin/csrf modules
I am supposed to make a basic Django app that receives user info(username, password, name, email) and checks they exist in the database already and returns 200 status if the info matches the one in the database. Also, if the database does not have such info, it should receive it on its signup page and stores in its database. The tricky part is that I am not supposed to use the Django functionalities like auth or admin or csrf. So basically, I have to emulate the Django functions from scratch. Below are what I have been working on so far. The project name is second_try directories account/models.py from django.db import models class Users(models.Model): username = models.CharField(max_length = 50) password = models.CharField(max_length = 300) email = models.CharField(max_length = 50) name = models.CharField(max_length = 50) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.objects.all() account/views.py import json from django.views import View from django.http import JsonResponse from .models import Users from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'index.html' class SignUp(TemplateView): template_name = 'signup.html' class AccountView(TemplateView): def post(self, request): data = json.loads(request.body) Users( username = data['username'], password = data['password'], email = data['email'], name = data['name'] ).save() return JsonResponse({'message':'SUCCESS'}, … -
How do I get the results of a multiple choice field from Django?
I set up a model multiple choice field, where a user can select multiple choices. I want to be able to get the choices that a user selected when filling out the form. What can I call to get the results that the user picked? Also, how would I iterate over those results (what does it return)? Here's the field: CHOICES = MyMultipleModelChoiceField(queryset=MODEL.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) Thanks! -
How to filter in Django DB based on calculations from different tables
I have 3 models from 3 different tables: class Profiles(models.Model): player_name = models.CharField(max_length=150) player_surname=models.CharField(max_length=200) class Meta: db_table='profiles' class Results_2019(models.Model): player_name = models.CharField(max_length=150) profiless=models.ManyToManyField(Profiles) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2019' class Results_2018(models.Model): player_name = models.CharField(max_length=150) profiless=models.ManyToManyField(Profiles) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2018' The database is static. Player in all three models have the same names =['Alex','Chandler','Zach'] and they all have data belonging to them for all columns ( first_score,second_score) Profiles database look like : id player_name player_surname 1 Alex Chapman 2 Chandler Wellington 3 Zach Berg Results_2019 database look like : id player_name first_score second_score 1 Alex 70 68 2 Chandler 60 62 3 Zach 90 85 Results_2018 database look like : id player_name first_score second_score 1 Alex 78 81 2 Chandler 56 66 3 Zach 97 95 I want to apply statictic analysis to players which involves math calculation based on values from Results_2019 and Results_2018 such as i want to get: - players whos growth in first_score and second_score in 2019 and in 2018 were more than 20% and then get the name and surnames who met these criteria and print in template. The below formula of criteria though does not work i show as guidance of what i want to … -
Filtering django querysets
In a project I have a view wich displays in the browser as a searchbar to search recipes. I think there is a better way then how I'm doing it right now, but have no idea how. If I don't do what I'm doing right now, I get the error that you can't filter with None. I know I could use a try exept but then none of the values may be None or an error is raised. class SearchResultListViewOther(ListView): model = Recipe template_name = 'recipes/search_other.html' extra_context = { 'time': time, 'categorie': categorie, 'continent': continent, } def get_queryset(self): """ Filter out recipes by some other params like the title """ # Can not filter on None so set a value if no search params were given title = self.request.GET.get('title') if not title: title = '0' time_recipe = self.request.GET.get('time') if not time_recipe: time_recipe = 0 continent_recipe = self.request.GET.get('continent') if not continent_recipe: continent_recipe = '0' object_list = Recipe.objects.filter( Q(title__icontains=title) | Q(time__lte=time_recipe) | Q(continent__exact=continent_recipe) ) return object_list -
Docker Pytest containers stay up after completing testing process
I've set my django project and now I'm trying to test it with pytest. What is issue running pytest withing my containers doesn't kill it at the end of the process. So at the end of day I'm stuck with multiple running containers from pytest and often postgreSql connection problems. My docker-compose file: version: '3' services: license_server: build: . command: bash -c "python manage.py migrate && gunicorn LicenseServer.wsgi --reload --bind 0.0.0.0:8000" depends_on: - postgres volumes: - .:/code environment: DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" DATABASE_PORT: "${DATABASE_PORT}" DATABASE_HOST: "${DATABASE_HOST}" env_file: .env ports: - "8000:8000" restart: always postgres: build: ./postgres volumes: - ./postgres/postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_PASSWORD: postgres DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" DATABASE_PORT: "${DATABASE_PORT}" DATABASE_HOST: "${DATABASE_HOST}" command: "-p 8005" env_file: .env ports: - "127.0.0.1:8005:8005" restart: always nginx: image: nginx:latest container_name: nginx1 ports: - "8001:80" volumes: - .:/code - ./config/nginx:/etc/nginx/conf.d depends_on: - license_server What I want to achieve is automatically closing containers after the testing process is finished. -
RabbitMQ Pika and Django Channels websocket
I am using Django Channels and RabbitMQ pika, for the first time. I am trying to consume from RabbitMQ queue. I am using Django Channels AsyncConsumer to group send it to everyone connected in the websocket. User type 1 : Can create a task User type 2 : Can accept the task. Use case : When user type 1 creates the task it is published in the rabbitmq. When it is consumed from the queue, it has to be group-sent to frontend. And when the user type 2 accepts the task other instances of user type 2 cannot accept the same and we consume from the queue again and send the next task in the queue to everyone. I have created the connection in a different thread using sync_to_async I am appending it to an in-memory list from the callback function. And whenever someone accepts I just pop it out of the list and acknowledge the queue. class AcceptTaskConsumer(AsyncConsumer): body = [] #IN MEMORY LIST delivery = {} #To store ack delivery_tag async def websocket_connect(self, event): print("AcceptTaskConsumer connected", event) AcceptTaskConsumer.get_task() #STARTS Queue listener in new thread self.room_group_name = "user_type_2" await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.send({ "type": "websocket.accept" }) async … -
How to optimize my code and the database access?
I'm creating a sme budingeting application, where I have the necessity to manage a lot of data ( huge list of products, balance sheet table etc.). I want to have an efficient and optimized code, respecting the DRY principle and less querysets possible to the database. Ad example this code in my views.py is it efficient and optimized? def conto_economico(request): # Creazione tabella materie prime, sussidiarie, di consumo e merci defaults = list(0 for m in range(12)) elements = dict() for conto_id, year, month, totale in(Materiale.objects.values_list('conto__nome', 'data__year', 'data__month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo')), output_field=FloatField())).values_list('conto__nome', 'data__year', 'data__month', 'totale').order_by("conto_id")) : if conto_id not in elements.keys(): elements[conto_id]=list(defaults) index=month-1 elements[conto_id][index]=totale total_elements={'Per materie prime, sussidiarie, di consumo e di merci': [sum(t) for t in zip(*elements.values())],} I utilize this code for a lot of model to create my tables, but I think that are not efficient. -
AWS Django project throws AttributeError at /contact when sending a form
I've been working on my first website with django, it's deployed to aws with zappa. The page is using Lambda, S3, Apigateway and cloudfront. When I get the api url from my terminal after deployment/update the form works fine. But when I try to send the form from my actual website urls I've set up in aws the website throws the following error: AttributeError at /contact 'list' object has no attribute 'lower' Request Method: POST Request URL: https://asdasdasd.execute-api.eu-west-1.amazonaws.com/my_bucket/contact Django Version: 2.1 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'lower' Exception Location: /var/task/django/utils/http.py in is_same_domain, line 278 Python Executable: /var/lang/bin/python3.8 Python Version: 3.8.2 Python Path: ['/var/task', '/opt/python/lib/python3.8/site-packages', '/opt/python', '/var/runtime', '/var/lang/lib/python38.zip', '/var/lang/lib/python3.8', '/var/lang/lib/python3.8/lib-dynload', '/var/lang/lib/python3.8/site-packages', '/opt/python/lib/python3.8/site-packages', '/opt/python', '/var/task'] Server time: Thu, 7 May 2020 06:13:04 +0000 My settings.py looks like this: """ Django settings for sciar_website project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ['DEBUG'] # EMAIL_HOST = ALLOWED_HOSTS = ['127.0.0.1', '(my_api_numbers).execute-api.eu-west-1.amazonaws.com', 'mywebsite.co/'] # Application definition INSTALLED_APPS = [ … -
Having trouble when migrating changes to the database - Python/Django
I was making some changes to the database in my project but i am facing some problems, it appears to not be a column in one of my tables but there it is, don't know what may be the cause of the problem, i'm not sure if it has to be with the onetoonefield relationships or what just broke it up entirely. Models from django.db import models # Create your models here. class BloodType(models.Model): Tipo = models.CharField(max_length=100) def __str__(self): return self.Tipo class Gender(models.Model): Genero = models.CharField(max_length=100) def __str__(self): return self.Genero class Nationality(models.Model): Nacionalidad = models.CharField(max_length=100) def __str__(self): return self.Nacionalidad class CivilStatus(models.Model): Estado = models.CharField(max_length=100) def __str__(self): return self.Estado class InsuranceCompany(models.Model): Compania = models.CharField(max_length=200) def __str__(self): return self.Compania class Policy(models.Model): Tipo_Poliza = models.CharField(max_length=256) def __str__(self): return self.Tipo_Poliza class Insurance(models.Model): Aseguradora = models.OneToOneField(InsuranceCompany,on_delete=models.DO_NOTHING) Tipo_de_Poliza = models.OneToOneField(Policy, on_delete=models.DO_NOTHING) Numero_de_poliza = models.CharField(max_length=100) Vencimiento = models.DateField() def __str__(self): return str(self.Aseguradora) + ' ' + str(self.Tipo_de_Poliza) class Patient(models.Model): Codigo = models.CharField(max_length=15) Nombre = models.CharField(max_length=100) Apellidos = models.CharField(max_length=200) Fecha_Nacimiento = models.DateField() Telefono = models.CharField(max_length=25,blank=True) Correo = models.EmailField(blank=True) Expediente = models.CharField(max_length=200, blank=True) Tipo_sangre = models.OneToOneField(BloodType,on_delete=models.DO_NOTHING) Peso = models.PositiveIntegerField() Estatura = models.PositiveIntegerField() Genero = models.OneToOneField(Gender,on_delete=models.DO_NOTHING) Nacionalidad = models.OneToOneField(Nationality,on_delete=models.DO_NOTHING) Estado_civil = models.OneToOneField(CivilStatus,on_delete=models.DO_NOTHING) Ocupacion = models.CharField(max_length=100,blank=True) Lugar_de_procedencia = models.CharField(max_length=100) Lugar_de_residencia = … -
How to add JS file in Django Admin just before the body tag
I am inserting two scripts into Djnago Admin as follows: class TutorialAdmin(admin.ModelAdmin): class Media: js = ( 'tutorials/js/ckeditor.js', 'tutorials/js/custom.js', ) formfield_overrides = { models.TextField: {'widget': Textarea( attrs={'id': 'custom_textarea'})} } Notice the formfield_overrides where I am adding an id custom_textarea to textarea tags so that I can get them later via javascript. If we look at my custom.js file: ClassicEditor .create( document.querySelector( '#custom_textarea' ) ) .catch( error => { console.error( error ); } ); This is the file which gets the element with id of custom_textarea. But the problem is that these files are added in the head tag so they run as soon as the page loads (before the textarea is rendered). I get the following error in the Chrome console: TypeError: Cannot read property 'appendChild' of null Is there a way where I can instruct Django to inject the custom.js just before the body tag? I know of a solution where I could edit my base.html in admin app. But I am wondering if there is a Django Way of doing this! Thanks. -
How to add user profile attributes to custom user model ( from AbstractUser ) in django admin panel? - StackInline
I saw an example in django document like this; from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from my_user_profile_app.models import Employee class EmployeeInline(admin.StackedInline): model = Employee can_delete = False verbose_name_plural = 'employee' class UserAdmin(BaseUserAdmin): inlines = (EmployeeInline, ) admin.site.unregister(User) admin.site.register(User, UserAdmin) I would like to use my custom user model with some extra fields (user_photo, user_credit...), so i wrote following code; accounts/models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) photo = models.ImageField(blank=True, upload_to='prof_pic/company', default='static/images/default_pp.png') credit = models.IntegerField(default=0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class FirmProfile(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='firmprofile_user') firm_name = models.CharField(max_length=200) class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name='userprofile_user') user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, default=1) and then accounts/admin.py class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'UserProfile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (UserProfileInline,) model = CustomUser list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(CustomUser, CustomUserAdmin) admin.site.register(FirmProfile) But i got "no such table: main.auth_user" error when … -
it has show error when i am poting data 'str' object has no attribute 'update'
@api_view(['GET', 'POST']) def compnay_list(request): """ List all Compnays, or create a new Compnay. """ if request.method == 'GET': compnay = Company.objects.all() serializer = CompanySerializer(compnay, many=True) return Response(serializer.data) elif request.method == 'POST': try: print(request.data.get('email')) user_id = User.objects.get(email=request.data.get('email')).id print(request.data) user_response = request.data.get('user_response') for item in user_response: item.update({"user": user_id}) serializer = CompanySerializer(data=user_response) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except User.DoesNotExist: print("Error:email not available") -
How do I create a MAX value for column referring to another table's column
class Agent(models.Model): nickname = models.CharField(max_length=64) club_agent_id = models.IntegerField() club = models.ForeignKey( Club, on_delete=models.CASCADE, related_name="agents") **rakeback** = models.DecimalField(max_digits=3, decimal_places=3) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="agents") def __str__(self): return f"{self.nickname} - {self.club} - {self.rakeback}" class Account(models.Model): nickname = models.CharField(max_length=64) club_account_id = models.IntegerField() **rakeback** = models.DecimalField(max_digits=3, decimal_places=3) club = models.ManyToManyField(Club, blank=True, related_name="accounts") agent = models.ManyToManyField(Agent, related_name="accounts") def __str__(self): return f"{self.club_account_id} - {self.nickname}" Here the program will create Agent and Account are tied to it. Account belongs to Agent. Agent has many Accounts. When creating Agent, the rakeback value is set by the User. How do I set MAX for rakeback on Account referring to the value of rakeback on Agent? -
How Do We Attach a Django User to a ModelForm
Our group is working on setting up a Django Project 'for fun' having users add and remove books to sell. However, we have run into a problem of trying to assign a logged in user automatically to the book they are adding through the AddBookForm(ModelForm). Trying something along the lines of Book.objects.get(AccountUser) just returns a list of all created accounts as well as Book.objects.filter(seller=request.user). We are only looking to automatically assign the current user that is logged in when they go to add a book but have had no success reading documentations and watching tons of tutorials. Any help would be greatly appreciated!! MODEL class Book(models.Model): NEW = 'NEW' USED = 'USED' CONDITION_CHOICES = [ (NEW, 'New'), (USED, 'Used'), ] FICTION = 'FICTION' NON_FICTION = 'NON-FICTION' POETRY = 'POETRY' DRAMA = 'DRAMA' EDUCATION = 'EDUCATION' GENRE_CHOICES = [ (FICTION, 'Fiction'), (NON_FICTION, 'Non-Fiction'), (POETRY, 'Poetry'), (DRAMA, 'Drama'), (EDUCATION, 'Education'), ] class Subject(models.IntegerChoices): architecture_and_construction = 0 arts_and_digital_arts = 1 business_and_management = 2 communications_and_media = 3 computing_and_mathematics = 4 criminal_justice = 5 education_and_teaching = 6 engineering_and_technology = 7 entrepreneurship = 8 exploratory = 9 government_and_administrations = 10 health_and_wellness = 11 humanities = 12 interdisciplinary_studies = 13 law_and_public_services = 14 medical_studies_and_sciences = 15 nursing_and_health_care … -
Cant display database values in django page
models.py from future import unicode_literals from django.conf import settings import requests import json from urllib.parse import quote from django.db import models class Company(models.Model): name = models.CharField(max_length=100, db_index=True) description = models.TextField(default='1') companyPhone=models.CharField(max_length=100,blank=True) companyWebsite=models.CharField(max_length=100,blank=True) companyIsPrivate=models.BooleanField(default=True) dividend=models.DecimalField(max_digits=7, decimal_places=2) priceEarningsToGrowthAndDividendYieldRatio=models.DecimalField(max_digits=7, decimal_places=2) price=models.DecimalField(max_digits=7, decimal_places=2) numberOfEmployees=models.DecimalField(max_digits=7, decimal_places=2) type=models.CharField(max_length=100,default='2') bicsIndustry=models.CharField(max_length=100,default='3') bicsSector=models.CharField(max_length=100,default='4') companyDescription=models.TextField(default='5') companyAddress=models.TextField(default='') priceToSalesRatio=models.DecimalField(max_digits=7, decimal_places=2) priceToBookRatio=models.DecimalField(max_digits=7, decimal_places=2) priceEarningsRatio=models.DecimalField(max_digits=7, decimal_places=2) totalAssets=models.DecimalField(max_digits=7, decimal_places=2, default=0.0) volume=models.DecimalField(max_digits=7, decimal_places=2,default=0.0) is_unique = models.BooleanField(default=True) def str(self): return self.name class Meta: db_table = 'post_company' view.py from django.forms import ModelForm from django.shortcuts import get_object_or_404, render from .models import Company def my_view(request): names = request.GET.get('name') instance = Company.objects.filter(pk=names).first() class ClientForm(ModelForm): class Meta: model = Company fields= '__all__' #fields = ('name', 'description','companyPhone','companyWebsite') form = ClientForm(instance=instance) return render(request,'pdf.html', {'form': form} ) display.py {% for field in form %} {{ field.label }} {% endfor %} {% for field in form %} {{ field.value }} {% endfor %} -
How to configure Django VPS location in URL request
I am trying to configure my Django app (Djnago 3.05) to work from a server location. The location is http://dev.apps.net/tac. How do i include this in each request? I managed to do this if adding in views.py the '/tac' prefix and add a folder named 'tac' in which all the templates exist. myviews.py @login_required def item_list(request): meta = "V1.1" if not any(field in request.GET for field in set(UserFilter.get_fields())): user_list = item.objects.order_by("-date").all()[:50] else: user_list = item.objects.order_by("-date").all() user_filter = UserFilter(request.GET, queryset=user_list) return render(request, "tac/items/item_list.html", {"filter": user_filter}) urls.py urlpatterns = [ url( r"^login/$", admin_views.LoginView.as_view(template_name="registration/login.html"), name="login", ), url(r"^$", TemplateView.as_view(template_name="home.html"), name="home"), url(r"^input/$", views.inputprocess, name="inputprocess"), url(r"^items/$", views.item_list, name="item_list"), url(r"^items/create/$", views.item_create, name="item_create"), url(r"^items/(?P<pk>\d+)/update/$", views.item_update, name="item_update"), url(r"^items/(?P<pk>\d+)/delete/$", views.item_delete, name="item_delete"), url(r"^reports/$", views.reports, name="reports"), url(r"^timeline/$", views.timeline, name="timeline"), url(r"^support/$", views.support, name="support"), url(r"^dbToools/$", views.dbTools, name="dbTools"), url(r"^logout/$", views.logout_view, name="logout_view"), url(r"^upload/$", views.upload, name="upload"), path("accounts/login/", auth_views.LoginView.as_view()), path("admin/", admin.site.urls), ] I am not sure if this is the correct way. How could I do this more efficient? Could you guys please gelp me here? Thanks! -
Django Filter: __exact lookup doesn't work although no lookup works
I want to use filters on my endpoint using Django Filters. My field is a boolean field, and I justs want to filter on the exact value. When query api/mybooks?is_read=true it works (no operator --> use exact instead, it is fine) if I use the exact operator explicitely api/mybooks?is_read__exact=true it doesn't work, the filter is ignored. my filter: class MyBookFilter(django_filters.FilterSet): class Meta: model = MyBook fields = { "is_read": ["exact"], } I use the default postgres sql database. Am I missing something? -
Django full text search with PostgreSQL, across multiple different models
I need to perform FTS across multiple different models. I want to get any model type in search result. I would like to sort results by rank, to get most relevant result. I can run search one by one, but not sure how can I combine results, especially preserving rank relevancy. Here are models, its an example from Making queries manual page. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() pub_date = models.DateField() mod_date = models.DateField() authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() rating = models.IntegerField() -
Edit Django files on Heroku without editing my database files
I wanna make some changes to my Django site running on Heroku, how can i upload my new changes with git push without touching my database, so i don't loose any data? -
How can I generate a dynamic shorturl with expiring time?
I have a python code with django that make shorturl with hash decoder, but it cannot generate dynamic code for especial full url. In fact i want to generate shorturl codes with expiring time so that when its time expired, i woud be able to generate new shorturl for my full url. Thanks you for your answers! model.py class URL(models.Model): full_url = models.URLField(unique=True) short_url = models.URLField(unique=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.id: self.short_url = md5(self.full_url.encode()).hexdigest()[:8] validate = URLValidator() try: validate(self.full_url) except ValidationError as e: raise GraphQLError('invalid url') return super().save(*args, **kwargs) -
Django Nginx Gunicorn Upstream Premature closed connection while reading response
nginx conf server { listen 80; server_name private.com; client_max_body_size 4G; client_body_buffer_size 8000M; client_body_timeout 120; proxy_connect_timeout 900s; proxy_read_timeout 900s; location = /favicon.ico { access_log off; log_not_found off; } autoindex on; location / { include proxy_params; proxy_pass http://unix:/home/dm/stat.cok; } } gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=Pa Group=www-data WorkingDirectory=/home/un/foldername ExecStart=/home/un/foldername/bin/gunicorn \ --access-logfile - \ --workers 3 \ --timeout 450 \ --bind unix:/home/dm/stat.sock scistat.wsgi:application [Install] WantedBy=multi-user.target I upload a large excel file 90mb size, It contains 450000+ rows and 6 columns. After the file upload, It calculate the row and columnf of excel file the multiply it to compute the total row and column of excel file, but this error show "upstream prematurely closed connection while reading response header from upstream" -
Django 3.0 App is not a registered namespace
I have the app_name as basicapp in the urls.py folder of my app but still when django says basicapp is not a registered namespace. here is my urls.py of basicapp from django.urls import path from basicapp import views from django.urls import include #template tagging app_label = 'basicapp' urlpatterns = [ path('relative/',views.relative,name='relative'), path('other/',views.other,name='other'), ] template file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Welcome to relative url</h1> <a href="{% url 'basicapp:other' %}"></a> </body> </html> Please let me know how to fix this mistake. -
Django channel not getting message
I am using django channel in my current project. From one of my django app, I am sending notification to the channel layer, so that websocket can broadcast the message. But problem is consumer is not getting my message. Utils in django app for sending notification to channel: from asgiref.sync import AsyncToSync from channels.layers import get_channel_layer import json def async_send(group_name, text): channel_layer = get_channel_layer() AsyncToSync(channel_layer.group_send)( group_name, { 'type': 'notify', 'text': json.dumps(text) } ) My consumer file is: from channels.generic.websocket import AsyncWebsocketConsumer class InformationConsumer(AsyncWebsocketConsumer): async def connect(self): self.channel_layer.group_add(str(self.scope['user']), self.channel_name) await self.accept() async def notify(self, event): await self.send_json( { "message": event['text'], }, ) print(event['text']) I am supposed to get the output of event['text'], but getting nothing :( -
ERROR 2026 - SSL connection error - Ubuntu 20.04
I've recently upgraded my local machine OS from Ubuntu 18.04 to 20.04, I'm running my MySQL-server on CentOS (AWS). Post upgrade whenever I'm trying to connect to MySQL server it is throwing SSL connection error. $ mysql -u yamcha -h database.yourproject.com -p --port 3309 ERROR 2026 (HY000): SSL connection error: error:1425F102:SSL routines:ssl_choose_client_version:unsupported protocol But if I pass --ssl-mode=disabled option along with it, I'm able to connect remotely. $ mysql -u yamcha -h database.yourproject.com -p --port 3309 --ssl-mode=disabled Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 22158946 Server version: 5.7.26 MySQL Community Server (GPL) Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> Queries: How to connect without passing --ssl-mode=disabled How to pass this --ssl-mode=disabled option in my Django application, currently I've defined it as shown below, but I'm still getting the same error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'yamcha', 'USER': 'yamcha', 'PASSWORD': 'xxxxxxxxxxxxxxx', 'HOST': 'database.yourproject.com', 'PORT': '3309', 'OPTIONS': {'ssl': False}, } -
how can I properly validate lesson modules per user rights?
I want to validate if my lesson material belongs to a xyz user with pro rights and each lesson has matched properly with the rights but if not it will display become a member , but however if I change the allowed_memberships id to pro only it doesnt work as expected it always goes to become member class UserMembership(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user.email id,stripe_customer_id,membership_id,user_id "1" "xxxxxx" "1" "63ce34cb8fe647a9bb1d28f61918e1bf" "3" "xxxxxx" "2" "c133546e6ed846c48a3938ccca8ffcbb" class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) def __str__(self): return self.membership_type id,membership_type,price,stripe_plan_id "1" "1" "Free" "0" "xxxxxxx" "2" "2" "Professional" "40" "xxxxxxx" class Lesson(models.Model): allowed_memberships = models.ManyToManyField(Membership) id,lesson_id,membership_id "1" "1" "1" "2" "2" "1" "3" "3" "1" "4" "4" "1" "5" "5" "1" "11" "6" "1" "64" "7" "2" views def get(self, request): template = loader.get_template(self.template_name) template_member = loader.get_template(self.template_payment) if UserMembership.objects.filter(user=request.user,membership_id=2).exists(): return HttpResponse(template.render()) else: return HttpResponse(template_member.render())