Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django different filters based on category
I couldn't find a question like mine. Basically, I want to create a complex filtering system. The user goes into different categories, and he will see different filters for the model based on the category he is at. It all needs to be on one HTML page. Any ideas? (Sorry if it's a bit hard to understand I just don't really know how to.) -
python crash course making django posts accessible to unregistered users
Im currently trying to do this exercise of python crash course and am unsure with how to proceed with it. Here is the exercise in question. Then try adding a more advanced feature, such as giving users the option of making a topic public. This would require an attribute called public as part of the Topic model (this should be set to False by default) and a form element on the new_topic page that allows the user to change a topic from private to public. Here are the changes that I have already made so far in forms.py, My understanding is that when the user types in the 'public' text bos either 'True' or 'False', the public attribute of the Topic model will be updated accordingly? from django import forms from .models import Topic, Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text', 'public'] labels = {'text': '', 'public' : "True/False"} class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labels = {'text': 'Entry:'} widgets = {'text': forms.Textarea(attrs={'cols': 80})} the Topic model in models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text … -
Django: Raw SQL Query with parameterized parameters
I'm trying to test the vulnerabilities of SQL injection using the Manager's raw() function in Django. I'm using SQLite as the backend database. I have tried the following two functions for showing the values of the Person Model that I have created. urls.py urlpatterns = [ path('unsafe/<str:user_name>', views.unsafe_get_users, name='unsafe_get_users'), path('safe/<str:user_name>', views.safe_get_users, name='safe_get_users'), ] models.py class Person(models.Model): name = models.CharField(max_length=30) age = models.IntegerField() def __str__(self): return self.name + " " + str(self.age) views.py from django.shortcuts import render from django.http import HttpResponse from .models import Person def unsafe_get_users(request, *args, **kwargs): # sqli using raw user_name = kwargs['user_name'] users = Person.objects.raw('SELECT * FROM member_list_person WHERE name = %s' % user_name) return HttpResponse(users) def safe_get_users(request, *args, **kwargs): # uses parameterized query user_name = kwargs['user_name'] users = Person.objects.raw('SELECT * FROM member_list_person WHERE name = %s', [user_name]) return HttpResponse(users) The Person Model has two fields, namely name and age. As for the unsafe_get_users function, the column data are displayed successfully but for the safe_get_users function, nothing shows up on the server page. I have tried printing len(users), which shows the number of data in the returned RawQuerySet, but for the second one it returns 0 (empty query). Why does unsafe_get_users function return the data as expected … -
django-rest-framework access field inside serializer
So I have a model like this class DataSheet(BaseModel): """ Represents a single dataSheet. dataSheets have their own model at the core. Model data is added to the dataSheets in the form of separate records. """ class Meta: verbose_name = 'datasheet' verbose_name_plural = 'datasheets' ordering = ['position', 'cluster'] required_db_features = { 'supports_deferrable_unique_constraints', } constraints = [ models.UniqueConstraint( fields=['position', 'cluster'], name='deferrable_unique_datasheet_position', deferrable=models.Deferrable.DEFERRED ) ] def __str__(self): return self.name objects = managers.DataSheetsManager() positions = managers.PositionalManager() position = models.PositiveSmallIntegerField(db_index=True, editable=True) name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True) description = models.CharField(max_length=1024, null=True, blank=True, db_index=True) owner = models.ForeignKey('api_backend.Member', on_delete=models.CASCADE, db_index=True, editable=False) fields = models.ManyToManyField('api_backend.Field') overwrites = models.ManyToManyField('api_backend.RoleOverwrite') parent = models.ForeignKey('api_backend.Category', on_delete=models.CASCADE, null=True, blank=True) cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False) REQUIRED_FIELDS = [name, owner, cluster] and a serializer like this class DataSheetSerializer(serializers.ModelSerializer): """ A serialized DataSheet Object. Datasheets have their own: - array of fields - array of role-overwrites """ def get_fields(self): fields = super(DataSheetSerializer, self).get_fields() fields['parent'].queryset = self.cluster.categories.all() return fields class Meta: model = DataSheet read_only_fields = ['position'] fields = '__all__' # need to make sure that the parent category of the datasheet # belongs to the datasheet's cluster only. fields = partial.PartialFieldSerializer(many=True, read_only=True) overwrites = partial.PartialOverWriteSerializer(many=True, read_only=True) the thing is, I want to access the serializer model's … -
Send a websocket message when exceptions is raised in django channels
I'm using django-channels. When an exception is raised within a consumer it will log the error, the websocket connection will be disconnected and then it will re-connect again. I would like to send a websocket message before it disconnects. I've tried to catch the error, send the message and then re-raise the exception. But the message still isn't sent. What's the best way of achieving this? -
Import current module from an imported module in python Django (importing loops)
Take the following pseudo-code for example models.py from django.db import models from django.core.exceptions import ValidationError from .methods import list_eligible_badges class User(models.Model): handle = models.SlugField(max_length=200) class Permission(models.Model): user = models.ForeignKey(User) badge = models.SlugField(max_length=200) def clean(self): super(Permission, self).clean() allowed_badges = list_eligible_badges() try: allowed_badges.index(self.badge) except: raise ValidationError('This user is not eligible for this privilege') methods.py from .models import User def list_eligible_badges(user_handle): user_in_context = User.objects.get(handle=user_handle) # do some validation on the user_in_context to figure out what # badge is this user eligible for then return a list of badges # allowed for this user The above code defines two related data models, User and Permission where each permission is associated with a user. and in the file methods.py we have a method, list_eligible_badges where this method takes the user_handle (unique slug identifier of a user) and returns a list of slugs for the permissions that this particular user is eligible for. And then the list_eligible_badges method is being used in the clean function of the Permission model to validate each permission before it's added to the database. Everything seems fine, except that when running the code, it shows the error: File "methods.py", line 1, in from .models import User ImportError: cannot import name 'User' … -
signup with OTP in django
i want to create a signup system for my users with django like below, 1- user enter phone_number 2- server store phone_number as a new user 3- server store a key-value pair in redis like this: phone_number : generated_token with five minute life time 4- server send a sms to user containing generated_token i have two question here: 1 - how should i create a new token? hotp or totp or urandom ? 2 - in case of a secure and safe generated_token, is this approach good ? i have little information about those 3 algorithm, but i need more thank you -
Django Form save successfully through url into database but not through bootstrap Modal Form
I'm trying to post data through bootstrap modal form. From all checks the data is post successfully but it doesn't save in database. Meanwhile data is save into database if form is accessed directly through add URL. Form save into database if accessed directly Form doesn't save into database when accessed through Modal form.html {% load widget_tweaks %} <form method="post" action="."> {% csrf_token %} <div class="modal-header"> <h4 class="modal-title">Add Bank</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <input type="hidden" name="action" value="{{ action }}"> {% if form.errors %} <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> <h5><i class="icon fas fa-ban"></i> An error occurred while trying to save the record!</h5> <ul> {% for field in form %} {% for error in field.errors %} <li>{{ error }}</li> {% endfor %} {% endfor %} </ul> </div> {% endif %} <div class="form-row"> {% for field in form %} <div class="form-group col-md-6"> <label for="{{ field.id_for_label }}">{{ field.label }}:</label> {% render_field field class="form-control" placeholder=field.label %} <div class="{% if field.errors %} invalid{% endif %}"> {% for error in field.errors %} <p class="help-block">{{ error }}</p> {% endfor %} </div> </div> {% endfor %} </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-success">Save <i class="fas fa-save"></i></button> <button … -
How can we create a page that allows user to create virtual machine in django
Basically I have a project with following milestones: Take user apis from user interface and save in db. Allow user to update api keys or add more keys. Then create page where user can create vm. ( basically you dont have to create vm, just call rest api to create one). List and manage those vms (you can either locally create table to store vm details or fetch from apis) in django.Please help! -
Unable to Save to Django Model
I am saving a Django model and everything works except for one column in the model and I can't seem to figure out what the issue is. I imagine just a fresh pair of eyes will see the likely basic error I am making. Here is an abbreviated snippet of my code: My model: class Commission(models.Model): checkout_id = models.CharField(max_length=20,null=True, blank=True) My function: def custom_order(custom_order_manager_data): from apps.commission.models.commission import Commission custom_order_id = custom_order_manager_data['customOrderId'] custom_order_data = Commission.objects.get(id=custom_order_id) custom_order_data.checkout_id = checkout.id #checkout works ignore this print("CHECKOUT ID: ",checkout.id) print("CUSTOM ORDER CHECKOUT Public ID: ",custom_order_data.checkout_id) custom_order_data.save() print("Post Save ",custom_order_data.checkout_id) When I check my logs, everything works and is printing the correct data, but it still isn't saving. Here are the logs: CHECKOUT ID: 3380 CUSTOM ORDER CHECKOUT Public ID: 3380 Post Save 3380 For me this shows that the instance is gathering the correct data and it is saved correct to that instance, but it won't save in the db (all other data does though, it's just specifically when I'm trying to save to checkout_id that isn't working. I am getting no errors. Here is what I've tried: I've changed the model name. I've changed the column name to something more unique. I've increased the … -
Django Pagination in nested field with Generics
i have following class class PersonSerializer(serializers.ModelSerializer): comments = CommentSerializer(source='comment_set', many=True) images = ImageSerializer(source='image_set', many=True) class Meta: model = Person exclude = ('paid', 'status', 'register_date', 'paid_date') which returns me info about user with nested comment field { "id": "718b309c-864d-4c26-a80e-2e744ac3102a", "comments": [ { "id": "6fc515bb-295a-4191-8255-da7f8fe7976e", "comment": "Test comment", "name": "Test", "age": 25, "comment_date": "2021-01-10T10:07:45.549207Z", "person": "718b309c-864d-4c26-a80e-2e744ac3102a" } ], "images": [], "name": "Test"} Class that handles query looks like class PersonListView(generics.ListAPIView): serializer_class = PersonSerializer permission_class = permissions.IsAuthenticatedOrReadOnly pagination_class = PageNumberPagination filter_backends = (DjangoFilterBackend,) filterset_fields = { 'city': ['exact'], 'age': ['gte', 'lte', 'exact', 'gt', 'lt'], } def get_queryset(self): queryset = Person.objects.filter(status=2, paid=False) return queryset I use PageNumberPagination as i default paginator. But nested field is not paginated. Is there any general way to do it with Generics ? -
Password is not being hashed when using Django Abstract User
I'm building a web application am using AbstractUser to create custom users. here are my models. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Meta: verbose_name = 'supplier' verbose_name_plural = 'suppliers' class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) class Meta: verbose_name = 'worker' verbose_name_plural = 'workers' admin.py from django.contrib.auth.admin import admin from .models import Worker , Supplier , User admin.site.register(Supplier) admin.site.register(Worker) Everything works fine until ti comes to saving users and there passwords. The passwords are not encryted both in the admin and my django rest urls . Is there a gerenal way to fix it in the User model directly without overiding the Serialisers create method so it works corectly for everything? If no how can I fixed the admin side too. -
how to view specific fields from db of two tables into html table in django?
how to combine specific fields in two tables in dbsqlite into html table in python django.how to call values into table <tbody id="tableSearch"> {% for instance in experiment_detail %} {% for instance in project_detail %} <tr> <!-- <td>{{ instance.id }}</td> --> <td>{{ instance.Experiments_name }}</td> <td>{{ instance.Experiments_remarks }}</td> <td>{{ instance.ProjectName }}</td> <td> class Experiments(models.Model): Experiments_name = models.CharField(max_length=100) Experiments_status = models.CharField(max_length=100) Experiments_project_id = models.ForeignKey('Project', on_delete=models.CASCADE) Experiments_testRatio = models.FloatField(default=0.0) Experiments_remarks = models.CharField(max_length=100,default='') class Project(models.Model): ProjectName = models.CharField(max_length=100) -
Django channels update playerlist on disconnect
I'm making a chat room with django-channels(websocket functionality). I have Room and Artist models and, I have two forms HostRoom and JoinRoom. I have a player list on the left of the screen. I'm able to update the player list in a room when a new user enters by broadcasting new playerlist to room. (running broadcast_msg_to_chat by catching m2m changed) However, I couldn't find a way to update the room player list when one of the artist leaves the room, I also need to delete disconnected artist instance from the room instance. I tried to update in onDisconnect using self.nickname inside consumer, but it deleted the the nickname of the last person who entered the room. How can I handle that? #forms.py class HostRoomForm(forms.ModelForm): class Meta: model = Artist fields = ['nickname', ] labels = { 'nickname': _('nickname'), } class JoinRoomForm(forms.ModelForm): temp_room_code = forms.CharField(max_length=6, min_length=6) class Meta: model = Artist fields = ['nickname', 'temp_room_code', ] labels = { 'nickname': _('nickname'), } #models.py class Room(models.Model): name = models.CharField(max_length=6) # make unique artists = models.ManyToManyField('Artist') active = models.BooleanField(default=False) class Artist(models.Model): nickname = models.CharField(max_length=30, default='') def __str__(self): return f'{self.nickname}' def artists_changed(instance, *args, **kwargs): artists_count = instance.artists.count() # broadcast playerlist to room if artists_count … -
Mac OS Big Sur update causing pip install requirements for django 1.11 with cffi error
Mac OS Big Sur update causing pip install requirements for django 1.11 with cffi error. How can I resolve this ? Running setup.py install for cffi ... error ERROR: Command errored out with exit status 1: command: /Users/axil/Documents/project/projectdotcom/projectdotcomenv_v2/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-install-nsm19ufc/cffi_73cb07cbfd52456caf370009aa7e0938/setup.py'"'"'; __file__='"'"'/private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-install-nsm19ufc/cffi_73cb07cbfd52456caf370009aa7e0938/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-record-y3_9oop2/install-record.txt --single-version-externally-managed --compile --install-headers /Users/axil/Documents/project/projectdotcom/projectdotcomenv_v2/include/site/python3.8/cffi cwd: /private/var/folders/gp/2f22kt6s75d8tf653xq_5rfh0000gn/T/pip-install-nsm19ufc/cffi_73cb07cbfd52456caf370009aa7e0938/ Complete output (65 lines): running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.8 creating build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/backend_ctypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/error.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/setuptools_ext.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/cffi_opcode.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/vengine_gen.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/model.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/ffiplatform.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/api.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/vengine_cpy.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/commontypes.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/lock.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/recompiler.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/cparser.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/verifier.py -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/_cffi_include.h -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/parse_c_type.h -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/_embedding.h -> build/lib.macosx-10.9-x86_64-3.8/cffi copying cffi/_cffi_errors.h -> build/lib.macosx-10.9-x86_64-3.8/cffi running build_ext building '_cffi_backend' extension creating build/temp.macosx-10.9-x86_64-3.8 creating build/temp.macosx-10.9-x86_64-3.8/c gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/local/Cellar/libffi/3.3/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/ffi -I/Users/axil/Documents/project/projectdotcom/projectdotcomenv_v2/include -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c c/_cffi_backend.c -o build/temp.macosx-10.9-x86_64-3.8/c/_cffi_backend.o c/_cffi_backend.c:4197:31: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers] … -
no such column: ecomapp_firstsliderdata.category_id why the category data is not deleting and showing this error in django
when i try to open column in no such column category_id why this is showing and also i'm not able to delete category list from DB my models.py class FirstSliderData(models.Model): image = models.ImageField() title = models.TextField(max_length=500) desc = models.TextField(max_length = 5000 ,null=True,blank=True) category = models.ForeignKey(Category , on_delete=models.CASCADE , default=1) brandName = models.TextField(max_length = 100,default='',null=True,blank=True) class TopList(models.Model): image = models.ImageField(upload_to='ProductImg') title = models.TextField(max_length=500) discountpercentage = models.IntegerField(blank=True,null=True) discountPrice = models.IntegerField(blank=True,null=True) brandName = models.TextField(max_length = 100 , default='',null=True,blank=True) desc = models.TextField(max_length=5000 ,null=True,blank=True) finalprice = models.IntegerField(blank=True,null=True) category = models.ForeignKey(Category , on_delete=models.CASCADE , default=1) @staticmethod def get_products_by_id(ids): return Product.objects.filter(id__in =ids) @staticmethod def get_all_products(): return Product.objects.all() @staticmethod def get_all_products_by_categoryid(category_id): if category_id: return Product.objects.filter(category = category_id) else: return Product.get_all_products() class Category(models.Model): name = models.CharField(max_length=20) @staticmethod def get_all_categories(): return Category.objects.all() def __str__(self): return self.name my admin.py file also the category list is not deleting from db it shows same error again when i try to delete like listed product i'm getting same errors from .models import FirstSliderData , TopList ,Category @admin.register(FirstSliderData) class FirstsliderModelAdmin(admin.ModelAdmin): list_display=['id','image','title' ,'category'] @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name'] -
Django RetrieveAPIView class with pagination
I have following class class CommentRetrieveView(generics.RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer pagination_class = PageNumberPagination permission_classes = (permissions.IsAuthenticatedOrReadOnly,) As a pagination class i set PageNumberPagination, but when i try to http://127.0.0.1:8000/api/comments/6fc515bb-295a-4191-8255-da7f8fe7976e my result is without pagination { "id": "6fc515bb-295a-4191-8255-da7f8fe7976e", "comment": "test comment", "name": "Test", "age": 25, "comment_date": "2021-01-10T10:07:45.549207Z", "person": "718b309c-864d-4c26-a80e-2e744ac3102a"} The default pagination class in settings is 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination' How to correctly use pagination in RetrieveAPIView? -
How could I create many radio inputs with for loop?
Here's my code: {% for answer in value %} <div class="answer"> <input type="radio" name="answer-checkbox" value="{{ answer.id }}"> {{ answer }} </div> {% endfor %} I want to create multiple sets of questions and answers, within each set only one answer could be selected at a time, how could I do this? -
How to not submit a form unless search is one of the options (django + HTML) [duplicate]
So I have the following code: <input autocomplete="off" type="search" list="liss" name="q" id="id_q" placeholder="Search"> <datalist id="liss"> <option value="one">Value 1</option> <option value="two">Value 2</option> <option value="three">Value 3</option> <option value="four">Value 4</option> <option value="five">Value 5</option> <option value="six">Value 6</option> </datalist> And it all works fine. The only thing I want it to do is to not let the user submit the form unless the input value is one of the options. How can I do that? -
A way to filter models for ModelChoiceField in Wagtail
Let's say I have a ForeignKey field in my model. class MyModel(StatusModel): site = models.ForeignKey('wagtailcore.Site', related_name='test_field', on_delete=models.CASCADE) panels = [ FieldPanel('site') ] Looks like Wagtail creates ModelForms by itself, but I need to filter models that make it to the dropdown list on my editing page. How can I do it? -
How do I include username (<str:username>) in my react native Endpoint
Please im learning react native and I am stuck, my problem is that I need to be about to use something like this in my react native (API): const endpoint = "/users/<username>/"; const getUser = () => client.get(endpoint); So the gist is, I want to dynamically pass the user's username in there, because thats the only way to get the details from the backend (REST API), When i use POSTMAN and get this http://127.0.0.1:8000/api/users/*username* it returns the needed data, but when I try that, even putting the username manually it doesnt work . Secondly, is there a way to get the user's username from jwt token and pass it into the react native endpoint. Id share my code below, Please bear with me: API URL PATH IN DJANGO: path('<str:username>/', profile_detail_api_view), path('<str:username>/follow', profile_detail_api_view), API CALL IN REACT NATIVE: import client from "./client"; const endpoint = "/users/que/"; (FOR INSTANCE HERE IM PASSING THE USERNAME DIRECTLY TO TEST) const getUser = () => client.get(endpoint); export default { getUser, }; PAYLOAD ON JWT SAMPLE: { "token_type": "access", "exp": 1611483456, "jti": "47907077556234bd9b6a9fa330f5ee", "user_id": 2 } I have tried a direct endpoint (blog) and it works, but that user part doesnt even though its the same … -
How to modify the form field types in the django CreateView form
I have a model that has a couple of date fields. I am using the CreateView along with a template. In the template, I am doing fairly standard code {% extends 'instructor_base.html' %} {% load crispy_forms_tags %} {% block title %} New Section {% endblock %} {% block content %} <h1>New Section</h1> <form method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success ml-2" type="submit">Save</button> </form> {% endblock %} However, when the form displays, the two date fields in the model are displayed as text boxes in the form. I would like them to display as date type. After several hours of going through documentation and tutorial sites, I can not figure out how to accomplish this. Everything I find is on how to override CreateView itself and not the form that goes with it. Any help with this would be greatly appreciated. -
Nginx stopped and failed to restart - open() "/run/nginx.pid" failed
I am running my django apis, deployed on Ubuntu 18, on Nginx and running via Supervisor. I am using Certbot for SSL certs and this is the only web service running on this webserver. No other websites are deployed here. The APIs went down today and nginx stopped working. I am not able to recreate why this happened, it had to be manually restarted. I have faced this once before and had similar error messages in the logs. Following are the nginx error logs. 2021/01/09 15:55:39 [crit] 9453#9453: *1331764 SSL_do_handshake() failed (SSL: error:1420918C:SSL routines:tls_early_post_process_client_hello:version too low) while SSL handshaking, client: <CLIENT IP ADDRESS>, server: 0.0.0.0:443 2021/01/09 20:39:55 [error] 9453#9453: *1337050 upstream prematurely closed connection while reading upstream, client: <CLIENT IP ADDRESS>, server: , request: "PUT /api/v1/APIURL/ HTTP/1.1", upstream: "http://127.0.0.1:8081/api/v1/APIURL", host: "<URL>", referrer: "<URL>" 2021/01/09 20:40:12 [error] 9453#9453: *1337057 upstream prematurely closed connection while reading upstream, client: <CLIENT IP ADDRESS>, server: , request: "PUT /api/v1/APIURL/ HTTP/1.1", upstream: "http://127.0.0.1:8081/api/v1/APIURL", host: "<URL>", referrer: "<URL>" 2021/01/09 20:41:02 [error] 9453#9453: *1337064 upstream prematurely closed connection while reading upstream, client:<CLIENT IP ADDRESS>, server: , request: "PUT /api/v1/URL/ HTTP/1.1", upstream: "http://127.0.0.1:8081/api/v1/URL/", host: "URL", referrer: "URL" 2021/01/10 03:51:29 [notice] 32527#32527: signal process started 2021/01/10 03:51:29 [error] 32527#32527: open() … -
How to include related models Django
I have 3 models: class ImageAlbum(models.Model): def default(self): return self.images.filter(default=True).first() def thumbnails(self): return self.images.filter(width__lt=100, length_lt=100) class Image(models.Model): name = models.CharField(max_length=255) image = models.ImageField(upload_to='images/') default = models.BooleanField(default=False) width = models.FloatField(default=100) length = models.FloatField(default=100) album = models.ForeignKey(ImageAlbum, related_name='images', on_delete=models.CASCADE) class Product(models.Model): title = models.CharField(max_length=300) price = models.IntegerField() description = models.TextField(max_length=2000, help_text="This is the description of the product") images = models.OneToOneField(ImageAlbum, related_name='model', on_delete=models.CASCADE) When I'm selecting product models Product.objects In the Product field images I'm having only the primary key of album. I want to get related ImageAlbum and all related Image for each ImageAlbum when I'm selecting Product model. Appreciate any help, thanks. -
Implement Page/Google-Login Counter with Django and Cookies?
I want to keep track: 1.) How many visitors went on my homepage 2.) How many logged in with the Google button For now I simply created with python a django-model: id url visitor_counter google_login_counter Everytime someone visits a page with the url x, it increases the visitor_counter. Everytime someone logs in with Google on the page x, it increases the google_login_counter. So far, so good, but now I have the problem, that if the user reloads the page, the counter increases again. I want to prevent this and wanted to ask what is the best solution? I was thinking about using cookies to check, if the user was already on the page? Is there a better solution or should I go with cookies?