Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django use Firebase Database for live messaging
I have a django application. I have 3 models: class ChatSession(models.Model): pass class ChatSessionMember(models.Model): pass class ChatSessionMessage(models.Model): pass These are stored in postgres. But I want them along with the User model saved in Firebase Database. On save and delete I want to make changes respectfully. The reason is because I want to use firebase database only for live messaging. How can I implement this firebase interaction? I looked at pyrebase but it seemed out of date. Its dependencies are too old and is not compatible with my django project. (other dependencies such as stripe use a more up to date request package) -
Is there any similar implementation of python sha1 in Java?
In a spring project I am trying to implement the Django like encryption logic for authentication because it will share the cookie with another python project. The issue I am facing is i am trying to sign the value in java in the same way its done in python. When I call value= hashlib.sha1(b'hello').digest() # the value i am getting is # b'\xaa\xf4\xc6\x1d\xdc\xc5\xe8\xa2\xda\xbe\xde\x0f;H,\xd9\xae\xa9CM' I have written this logic in Java which is not the same value as python. private static void getKey(String key) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); String result = DatatypeConverter.printHexBinary(md.digest("hello".getBytes())); System.err.println("result===>>>" + result); //the output is 204C417A627048ABE163CAF06434DDAD62FC9BF7 } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } Is there any way I can get the same value in Java ? -
Django- One-to-One "This field must be unique."
I have problem when try to update field in my Django app. I have One-to-One Relationship Partner to Incident. When i'm try to update, i got error partner: ["This field must be unique."]. In my ModelViewset class IncidentViewset(viewsets.ModelViewSet): queryset = Incident.objects.all() serializer_class = IncidentSerialzer def update(self, instance, validate_data): partner_id = request.data.get('partner') try: instance = Incident.objects.get(partner_id=partner_id) except Incident.DoesNotExist: instance = None serializer = IncidentSerializer(instance, data=request.data) if serializer.is_valid(raise_exception=True): # create or update data instance.interviewer = validate_data.get( 'interviewer', instance.interviewer) instance.interview_date = validate_data.get( 'interview_date', instance.interview_date) instance.interview_phone = validate_data.get( 'interview_phone', instance.interview_phone) instance.save() return Response(serializer.data) Any help?? Thanks in advance.. -
I can't add data to the database through form
I have been working on making a website in which people can post the evaluation of the restaurant they visited. I want users to post data through a form, but I can't make a form page work as I imagined. To speak the detail, the data put in the form isn't added to the database. Please tell me why the system doesn't work. I can't find the data I typed in the form on admin page and "Tabelog/list.html". The function named "form" is the one trying to show the form on the page and save data to the database. models.py from django.db import models stars = [ (1,"☆"), (2,"☆☆"), (3,"☆☆☆"), (4,"☆☆☆☆"), (5,"☆☆☆☆☆") ] # Create your models here. class Tabelog(models.Model): store_name = models.CharField("店名",max_length = 124) evaluation = models.IntegerField("評価",choices = stars) comment = models.TextField("口コミ") def outline(self): return self.comment[:10] def __str__(self): return ("{},{},{}".format(self.store_name,self.evaluation,self.comment[:10])) forms.py from django import forms from django.forms import ModelForm from Tabelog.models import Tabelog class CreateTabelogForm(forms.ModelForm): class Meta: model = Tabelog fields = "__all__" urls.py from django.urls import path,include from Tabelog import views app_name = "Tabelog" urlpatterns = [ path("lp/", views.lp,name="lp"), path("list/",views.list,name="list"), path("detail/<str:store_name>",views.detail,name="detail"), path("form/",views.form,name="form") ] views.py from django.shortcuts import render from Tabelog.models import Tabelog from Tabelog.forms import CreateTabelogForm # Create … -
Access @property method in reverse relation serialization DRF
I have these models: class Datas(BaseModel): path = models.CharField() folder = models.ForeignKey(folder, on_delete=models.CASCADE) class Photos(BaseModel): data = models.ForeignKey('Datas', on_delete=models.CASCADE) name = models.CharField() @property def file_path(self): return urljoin(self.data.folder.url, quote(self.full_path)) And these serializer for Datas model: class DatasSerializer(serializers.ModelSerializer): path = serializers.CharField() file_url = serializers.SerializerMethodField() class Meta: model = Datas fields = ( 'id', 'path', 'folder', 'file_url' ) def get_file_url(self, obj): return Photos.file_path What I want is to retrieve file_path from Photos model. Is it possible to access property method this way in reverse relation? -
Django Compressor: How to manage manifest.json for Offline Compress with multiple servers?
I have setup multiple servers with Django Compressor. So my settings.py AWS_ACCESS_KEY_ID = 'blablabla' AWS_SECRET_ACCESS_KEY = 'blablablabla' AWS_STORAGE_BUCKET_NAME = 'my-bucket-name' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'app_name.storage_backends.CachedS3Boto3Storage' # s3 media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'app_name.storage_backends.PublicMediaStorage' COMPRESS_ENABLED = True COMPRESS_URL = STATIC_URL COMPRESS_STORAGE = STATICFILES_STORAGE COMPRESS_CSS_FILTERS = [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter' ] COMPRESS_PARSER = 'compressor.parser.HtmlParser' COMPRESS_OFFLINE = True I got 3 servers. A utility server to execute "manage.py compress" to create a manifest.json file and "collectstatic" to S3 and 2 other application servers have to share the manifest.json file. So What i did is that I made a git repository to update manifest.json. So in utility server, I create one and push to a remote repository and connect to the other 2 application servers to pull the recent manifest.json under CACHE directory. This is what I've done so far to share manifest.json. Is there better approach or idea to handle this problem? -
Django signals can't change global variable
I am making a site where you can have a main goal, and split that into subgoals. I'm trying to grab the deleted instances root parent in the pre_delete function, set that instance to the "goal" variable, and then send that to my post_delete function which updates the entire tree for that "goal" variable. Now my problem arises, How do i get my "goal" variable from my pre_delete to my post_delete I tried setting a global goal value like shown below. but it hits me with " 'str' object has no attribute 'get_descendants' ". So it obviously isn't changing the global variable goal = '' @receiver(pre_delete, sender=Goal) def delete_goal(sender, instance, *args, **kwargs): root = instance.get_root() children = root.get_children() global goal for each in children: if each == instance: goal = each break else: desc = each.get_descendants() if instance in desc: goal = each @receiver(post_delete, sender=Goal) def delete_goal(sender, instance, *args, **kwargs): global goal gd = goal.get_descendants(include_self=False) for goal in gd: parent_progress = goal.parent.progress siblings = goal.get_siblings(include_self=True) result = parent_progress / len(siblings) itself = Goal.objects.filter(pk=goal.pk) itself.update(progress=result) print("Found!") -
Django spirit in create topic when generate error of Could not find config for '%s' in settings.CACHES"
I integrate with django project with spirit and after spirit in create topic then generate error in Could not find config for '%s' in settings.CACHES". -
"GET /reset_password/ HTTP/1.1" 302 0 in django
can you tell me why Obtain 302 that time i am reset password in Django i am automatic redirect login page how i fix this error please tell me urls.py path('reset_password/',auth_views.PasswordResetView.as_view()), In terminal [03/Jul/2020 11:01:16] "GET /reset_password/ HTTP/1.1" 302 0 -
Unable to create a collection in MongoDb atlas using Django RestApi framework
So basically i created a new Django project and an app which contains my model. I have already createed a free cluster on mongoDb atlas and connected my project via Djongo engine. Issues: when i first made make migrations and then migrated my model , it created a new database from scratch since i had not created it. however my model name is Mtsdata and would like to create a corresponding collection. why is the collection not created though it shows in the migration files that i have created the model and also in my database , my django_migrations is updated ? from django.db import models class Mtsdata(models.Model): Company = models.CharField(max_length= 32 , null=True, blank=True) plant = models.CharField(max_length= 32 , null=True, blank=True) class Meta: managed = False db_table = "Mtsdata" 'this is the urls.py file' from django.contrib import admin from django.urls import path from interndata import views urlpatterns = [ path('admin/', admin.site.urls), path('mtsdata/',views.Mtsdatalist.as_view()), ] 'this is the views.py file' from django.shortcuts import render from . models import Mtsdata from django.http import HttpResponse from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, ListAPIView # Create your views here. class Mtsdatalist(ListAPIView): def get(self,request): queryset = Mtsdata.objects.all() return Response(queryset.values()) -
'dict' object has no attribute 'iterkeys'
i have used params.keys() instead of params.iterkeys() but it doesn't resolve the problem i unable to find where's the problem. import base64 import string import random import hashlib from Crypto.Cipher import AES IV = "@@@@&&&&####$$$$" BLOCK_SIZE = 16 def generate_checksum(param_dict, merchant_key, salt=None): params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_refund_checksum(param_dict, merchant_key, salt=None): for i in param_dict: if ("|" in param_dict[i]): param_dict = {} exit() params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_checksum_by_str(param_str, merchant_key, salt=None): params_string = param_str salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def verify_checksum(param_dict, merchant_key, checksum): # Remove checksum if 'CHECKSUMHASH' in param_dict: param_dict.pop('CHECKSUMHASH') # Get salt paytm_hash = __decode__(checksum, IV, merchant_key) salt = paytm_hash[-4:] calculated_checksum = generate_checksum(param_dict, merchant_key, salt=salt) return calculated_checksum == checksum def verify_checksum_by_str(param_str, merchant_key, checksum): # Remove checksum # if 'CHECKSUMHASH' in param_dict: # param_dict.pop('CHECKSUMHASH') # Get salt paytm_hash = … -
How can I send a list from backend to django template?
I am trying to send a list of object to django template Here is my views.py: def index(req): labels = ['hello', 'yoooo', 'wassup'] values = [] chart_data = { 'y': json.dumps(labels), } return render(req, 'index.html', chart_data) Here is my django template index.html: <script type="text/javascript"> var endpoint = "/api/chart/data/"; var x = `{{y | safe}}`; console.log(x); </script> So when I use json.dumps it gave me a string of ['hello', 'yoooo', 'wassup'] and not a list. -
Get result joining 5 models in Django
i want a set of data joining 4 models. class Device(models.Model): DeviceId = models.AutoField(primary_key=True, db_column='DeviceId') DeviceName = models.CharField(max_length=50, null=True, default=None, blank=True) DeviceCode = models.CharField(max_length=25, null=False, blank=False, unique=True) Camera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId') DeviceType = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') class Meta: db_table = "Device" class Employee(models.Model): EmployeeId = models.AutoField(primary_key=True, db_column='EmployeeId') EmployeeCode = models.CharField(max_length=50, unique=True, default=None) EmployeeName = models.CharField(max_length=50) EmployeeStatus = models.BooleanField(default=True, null=True, blank=True) Device = models.ManyToManyField(Device, through='EmployeeDevice') class Meta: db_table = "Employee" class EmployeeDevice(models.Model): EmpDeviceId = models.AutoField(primary_key=True, db_column='EmpDeviceId') Employee = models.ForeignKey(Employee, db_column='EmployeeId', on_delete=models.CASCADE) Device = models.ForeignKey(Device, db_column='DeviceId', on_delete=models.CASCADE) class Meta: db_table = "EmployeeDevice" class RFID(models.Model): RFID = models.AutoField(primary_key=True, db_column='RFID') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, db_column='EmployeeId') RFIDCode = models.BigIntegerField(unique=True, default=None, null=False, blank=False) class Meta: db_table = "RFID" class FingerPrintInfo(models.Model): FingerPrintId = models.AutoField(primary_key=True, db_column='FingerPrintId') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, db_column='EmployeeId') FingerData = models.CharField(max_length=50) class Meta: db_table = "FingerPrintInfo" i want to loop the Device Model, For Each DeviceCode i want to get the Employee added to the device and get the details from RFID and FInger Print info for each employees. How can i do this. -
Virtualenv Issue: Django Project
I had created and activated virtualenv and worked on my Django Project. Now scene is that i've Reinstall my Windows 10. Now when i tried to enter my env e.g. workon DFMS I face following error... 'workon' is not recognized as an internal or external command,operable program or batch file. Or When i tried to run server using python manage.py runserver i face following issue... ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? My Question is how to activate that old virtualenv for that project? and how to resolve this problem? Thank You. -
Error while connecting reactjs axios with django rest framework to make the post request. but i am getting 500 (Internal Server Error)
I think i made incorrect post request. the get request works properly. since i am newbie in djangorestframework. while searching in google it says it is error in server side so i believe there is no problm in axios code. so please help me out here is axios code: axios({ method: 'post', url: 'http://127.0.0.1:8000/api/form/', data: this.state, headers: { 'Content-Type': 'application/json'} }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); } here is views.py class formAPI(APIView): def get(self,request): formData=Form.objects.all() serializer=FormSerializer(formData,many=True) return Response(serializer.data) def post(self,request): request.content_type('application/json') Fprov=request.data.query_params('selectedPro') Fdist=request.data.query_params('selectedDistrict') FpalikaT=request.data.query_params('selectedPalikaType') FpalikaN=request.data.query_params('enteredPalikaName') FWardN=request.data.query_params('enteredWardNo') FWardOf=request.data.query_params('enteredWardOfficeAddress') FWardC=request.data.query_params('enteredWardContactNo') FX=float(request.data.query_params('enteredXCords')) FY=float(request.data.query_params('enteredYCords')) FChaipersonN=request.data.query_params('enteredChairPersonName') FChairpersonC=request.data.query_params('enteredChaiPersonContact') FSecN=request.data.query_params('enteredSecretaryName') FSecC=request.data.query_params('enteredSecretaryContact') FArea=request.data.query_params('enteredArea') FHouseholds=request.data.query_params('enteredHouseholds') FPop=request.data.query_params('enteredTotalPop') FFepop=request.data.query_params('enteredMalePop') Fmapop=request.data.query_params('enteredFemalePop') FWeb=request.data.query_params('enteredWebsite') FEmail=request.data.query_params('enteredEmail') new=Form(Province=Fprov, District=Fdist, PalikaType=FpalikaT, PalikaName=FpalikaN, Ward_No=FWardN, Ward_Office_Address=FWardOf, Ward_Contact_No=FWardC, X_Cords=FX, Y_Cords=FY, Chairperson_Name=FChaipersonN, Chaiperson_Contact_No=FChairpersonC, Secretary_Name=FSecN, Secretary_Contact_No=FSecC, Area=FArea, Total_Households=FHouseholds, Total_Population=FPop, Total_Male_Population=Fmapop, Total_Female_Population=FFepop, Website=FWeb, Email=FEmail, location=Point(FX,FY, srid = 4326)) new.save() here is my serializers.py from rest_framework import serializers from .models import Form class FormSerializer(serializers.ModelSerializer): class Meta: model = Form fields = '__all__' and here is urls.py from django.contrib import admin from django.conf.urls import url from django.urls import path, include # add this from rest_framework import routers # add this from formback import views from rest_framework.urlpatterns import format_suffix_patterns router = routers.DefaultRouter() # add this router.register(r'form', views.FormView, 'Form') urlpatterns = [ … -
What is the correct way to submit Django inline formsets with prefilled data in a modal form
In my Django app, I am querying the database tables using jquery ajax call to fill inline formsets with the json callback data. The following image is a likely situation at the start of the process. The form/formsets are housed in a modal to conserve space. I am wanting to save the user input/s (including the pre-filled values) in the respective tables by submitting the form using ajax. The forms are: class mappedTargModelForm(forms.ModelForm): class Meta: model = mappedTargModel fields = ('mapper_doc_type', 'mapper_name', 'mapper_target_model', 'mapper_long_text') widgets = { 'mapper_doc_type': forms.TextInput(...), 'mapper_name': forms.TextInput(...), 'mapper_target_model': forms.TextInput(...), 'mapper_long_text': forms.Textarea(...), } class mappedTargFieldsForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(mappedTargFieldsForm, self).__init__(*args, **kwargs) self.auto_id = False class Meta: model = mappedTargFields fields = ('mapped_field', 'mapped_field_verb_name', 'mapped_field_col_name', 'mapped_field_fk_table') widgets = { 'mapped_field': forms.TextInput(...), 'mapped_field_verb_name': forms.TextInput(...), 'mapped_field_col_name': forms.TextInput(...), 'mapped_field_fk_table': forms.TextInput(...), } exclude = () CreateMappedTargFieldsFormset = inlineformset_factory( mappedTargModel, mappedTargFields, form=mappedTargFieldsForm, extra=2, can_delete=False) The view as adapted from (https://docs.djangoproject.com/en/2.2/topics/class-based-views/generic-editing/#ajax-example) is shown below: class AjaxableResponseMixin: """ Mixin to add AJAX support to a form. Must be used with an object-based FormView (e.g. CreateView) """ def form_invalid(self, form): response = super().form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): # We make sure to call the parent's form_valid() method because … -
Django - NoReverseMatch at /.... Reverse for ... with arguments ("",52)
Have looked through a lot of similar NoReverseMatch Errors and couldn't solve my problem. This is in Django. I keep getting: NoReverseMatch at /equipment32 Reverse for 'equipment' with arguments '('', 32)' not found. 1 pattern(s) tried: ['equipment(?P<equipment_id>[0-9]+)$'] Here is the traceback: Traceback (most recent call last): File "C:\ProgramData\Miniconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\ProgramData\Miniconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Miniconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Albert\Desktop\HARVARD CS50\tracker_django\tracker\views.py", line 128, in equipment return render(request, "jobs/equipment.html", context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\ProgramData\Miniconda3\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) … -
Compress wave file in python
I'm using Django framework and I received a wave file of size 8MB. I need to reduce the size of the file. How do I do that in python 2? Note: I have recorder the file through the recorder.js. I didn't find any solution to reduce it through javascript. So I need to reduce its size in python. -
Django Pagination Keep Current URL Parameters
I am developing a blog website using Django. On the home page, I have a list of posts, and they are viewed using pagination. On the same home page, I also have the functionality to do a text search (i.e. search for posts with a given text). For example, if I search for "hello", then the URL is: http://localhost:8000/?q=hello. Then, I want to go to the second page in the pagination, and I expect the URL to look like this: http://localhost:8000/?q=hello&page=2. However, instead, I get this URL: http://localhost:8000/?page=2. So, basically, when I navigate through pages, I want my pagination to keep the existing "q" parameter in the current URL. The problem is that the "q" parameter is gone when navigating though the pages. How do I fix this? This is my pagination: <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}"><i class="previous fa fa-arrow-left fa-lg"></i></a> {% endif %} <span class="current"> {{ page.number }} of {{ page.paginator.num_pages }} </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}"><i class="next fa fa-arrow-right fa-lg"></i></a> {% endif %} </span> </div> -
ERROR: EXPECTED TIME DELTA AND GOT DATETIMEFIELD INSTEAD ALSO TIMEDELTA IS NOT DEFINED
import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def str(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text -
Django two factor auth and Cisco Duo
I wanted to ask on https://github.com/Bouke/django-two-factor-auth but they are directing questions away from their issue tracker to SO. I need to add 2 factor auth to a django app but the client is insisting on using Cisco Duo https://duo.com/docs How do I use Duo with django-two-factor-auth project? I see there is a TWO-FACTOR-SMS-GATEWAY and duo has a python sdk https://github.com/duosecurity/duo_python a django example is available at https://github.com/duosecurity/duo_python/tree/master/demos/django Do I need to add a new type of gateway to the project like this? import logging import duo_web from django.conf import settings logger = logging.getLogger(__name__) class Duo(object): @staticmethod def make_call(device, token): logger.info('Fake call to %s: "Your token is: %s"', device.number.as_e164, token) @staticmethod def send_sms(device, token): duo_web.sign_request( settings.DUO_IKEY, settings.DUO_SKEY, settings.DUO_AKEY, duo_username(request.user)) -
ERR_CONNECTION_TIMED_OUT while deploying django using AWS elastic beanstalk(with nginx + gunicorn)
I'm facing ERR_CONNECTION_TIMED_OUT while deploying django using aws elastic beanstalk. Current status Console shows that it's properly deployed. (shows OK status to me) Allow inbound traffic for security group. However, when I tried to connect instance using the url the elastic beanstalk provide, I've been always seeing ERR_CONNECTION_TIMED_OUT on chrome browser. Things I've tried. Checked nginx log, and there's nothing printed out. So I suspect that Load balancer didn't route request to nginx web server. tail -f /var/log/nginx/* Connected ec2 instance using ssh, and checked nginx running with port 80 and gunicorn running with port 8000 [ec2-user@ip-172-31-0-29 ~]$ sudo lsof -i -P -n | grep LISTEN rpcbind 2650 rpc 8u IPv4 16321 0t0 TCP *:111 (LISTEN) rpcbind 2650 rpc 11u IPv6 16324 0t0 TCP *:111 (LISTEN) master 3130 root 13u IPv4 18639 0t0 TCP 127.0.0.1:25 (LISTEN) sshd 3328 root 3u IPv4 20466 0t0 TCP *:22 (LISTEN) sshd 3328 root 4u IPv6 20475 0t0 TCP *:22 (LISTEN) ruby 3475 healthd 6u IPv4 22081 0t0 TCP 127.0.0.1:22221 (LISTEN) nginx 4778 root 6u IPv4 392465 0t0 TCP *:80 (LISTEN) nginx 4780 nginx 6u IPv4 392465 0t0 TCP *:80 (LISTEN) gunicorn 4796 webapp 5u IPv4 392820 0t0 TCP 127.0.0.1:8000 (LISTEN) gunicorn 4806 webapp 5u … -
How to make a django model field where the content increases by a unit after every year
Actually I have a student model and a field called grade where i want the grade of every student to increase by 1 after every year -
Pass in Django Template Variable to JS function
In one of my templates, I have a for loop that goes over all the items. When a person likes or dislikes an item, I want to handle that with my function. Setting the button's HTML to something like this works: <button onclick='update_like(arg1, arg2)'></button>{{ item.id}} However, I need to pass my template variables to the function. So I tried something like this: <button onclick='update_like({{item.id}}, {{item.name}})'></button>{{ item.name}} But clicking the button just ouputs: Uncaught SyntaxError: Unexpected token 'default' This is a trimmed down version of the full template I'm using: {% extends 'base.html' %} {% load static %} {% block content %} <div class="list"> {% for item in items %} <button onclick='update_like({{item.id}}, {{item.name}})'></button>{{ item.name}} {% endfor %} </div> <script> var count = {}; function update_like(item_id, item_name) { count[item_id] = 1; console.log(count); return; } </script> {% endblock %} -
How to create a Post without a Form Model?
I am trying to figure out more about Post Method so my question's purpose is to understand how to Create a Post without a Form is it possible or not. Here is what I am trying to know how to do. I have a project where I want a user to submit a button without any forms or input from user's side only clicking on the button on the page, after pressing on the button the views are set to change a boolean field so that admin can be notified as an example. Here is what I was thinking about in the model: class Item(models.Model): active = models.BooleanField(default=False) Here is the views.py: class ChangeItemStatus(View): def post(self, *args, **kwargs): if form.is_valid(): item.active = True item.save() messages.success(self.request, 'Item Status has been Change To Active') return redirect("app:template_name") Sorry for the noobish question aiming to have a simplified explanation with this simple example