Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How could I display the employees information on the modal?
How to make that after clicking the view modal button on my index it will show that specific employee information? And at same time I will be able to edit those in future. -
Stuck on apache2 default page while deploying Django website
I have gone through a few answers on the web and I am still struggling to get past the apache2 default page. The webapp works fine locally and without apache. I am using an AWS EC2 instance for this on an ubuntu machine. The whole code is hosted in /home/ubuntu/sm on the machine, the venv is in /home/ubuntu/sm/venv and running on the ip addr 3.X.X.212 I've tried adding, editing, removing a few variables, to no avail. I got nothing in the error logs either. The 'gracefully restarting' entries are starting to look narcissistic given how long I've been stuck on this. apachectl -S produces the following response: [Tue Nov 05 05:16:52.198045 2019] [alias:warn] [pid 13664:tid 139764718218176] AH00671: The Alias directive in /etc/apache2/sites-enabled/sm.conf at line 33 will probably never match because it overlaps an earlier Alias. VirtualHost configuration: *:80 ip-172-*-*-29.ap-southeast-2.compute.internal (/etc/apache2/sites-enabled/sm.conf:1) ServerRoot: "/etc/apache2" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/var/log/apache2/error.log" Mutex default: dir="/var/run/apache2/" mechanism=default Mutex watchdog-callback: using_defaults PidFile: "/var/run/apache2/apache2.pid" Define: DUMP_VHOSTS Define: DUMP_RUN_CFG User: name="www-data" id=33 not_used Group: name="www-data" id=33 not_used "sm.conf" is the config file used for this, as below: ServerAdmin webmaster@localhost LogLevel info ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /robots.txt /home/ubuntu/sm/website/static/robots.txt Alias /favicon.ico /home/ubuntu/sm/website/static/favicon.ico Alias /static/ /home/ubuntu/sm/website/static Alias /static/ /home/ubuntu/sm/media … -
how call other class base view method in django
I want to make xlsx file per model. There are many models. They had each ListView(Class based view). So, I want to use these view's get_queryset method for making queryset. for example: testView = TestListView() queryset = testView.get_queryset() But, It's not working. I try this: testView = TestListView.as_view()(request) queryset = testView.get_context_data(request) but also didn't work. I need help. -
Django Signals: The QuerySet value for an exact lookup must be limited to one result using slicing
I hope my title is enough to determine what the error is. i have this code in my models.py (post_save) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, *args, **kwargs): teachers = SubjectSectionTeacher.objects.filter(Sections=instance.Section,Education_Levels=instance.Education_Levels,Courses=instance.Courses) for each in teachers: if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( pk=each.id, Students_Enrollment_Records=instance, Subject_Section_Teacher=teachers.all() ) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) class SubjectSectionTeacher(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) when I used the Subject_Section_Teacher=teachers.first() i received no error but that is not what i want result, then i decide to change it to this Subject_Section_Teacher=teachers.all() i just want the result to become this not this -
Trying to show custom success message and hide default success message in Django admin
<-- In admin.py I have a function it showing my custom message but also showing default success message how to stop default success message ??--> from django.contrib import messages, admin def save_model(self, request, obj, form, change): self.message_user(request, "The message", level=messages.SUCCESS) -
Has anyone tried creating a Web Socket that listens to Django channels web socket API?
I am trying to create a service that will listen to a web socket API from Django channels. I believe direct integration as with socket.io is not possible. Anyone can help me with this problem? I want an angular client to receive a list of coordinate changes and then reflect it to a map in real-time. -
NoReverseMatch at /kitty_view Reverse for 'kitty' with arguments '(5,)' not found. 1 pattern(s) tried: ['kitty$']
//While rendering this kitty_view i am getting this error. Exactly same thing i have copied from another app which is working properly. Kindly help. // Codes that i am using View.py --------- def kitty_view(request): kitty_list = kitty.objects.all().order_by('-cretime') code1 = str(request.GET.get('Code')) name1 = str(request.GET.get('nam')) status1 = str(request.GET.get('stat')) if (name1 is not None and name1 != ''): kitty_list = kitty_list.filter(name=name1) if (code1 is not None and code1 != ''): kitty_list = kitty_list.filter(code='K00001') if (status1 is not None and status1 != ''): kitty_list = kitty_list.filter(status = 'A') ctx = {'kitty': kitty_list} return render(request, 'kitty/kitty_view.html', ctx) URL.py -------- urlpatterns = [ path('',views.index,name='index'), path('kitty',views.kitty_save,name='kitty'), path('kitty_view',views.kitty_view,name='kitty_view') ] Template -------- {% extends 'base.html' %} {% load static %} {% block content %} <form class="form-signin" action="{% url 'kitty_view' %}" method="get"> {% csrf_token %} <div class="form-row"> <div class="mb-3"> <select class="custom-select center-block" name="code" id="code"> <option value="">Choose Kitty...</option> <!-- <option>{{ kitty1.code }}</option> {% for i in kitty1 %} <option value="{{ i.code }}"> {{ i.code|add:' - '|add:i.name }} </option> {% endfor %} --> <option>K00004</option> <option>K00005</option> </select> </div> <div class="mb-3"> <input type="text" name="nam" id="nam" class="form-control-sm center-block" placeholder="Name" autofocus> </div> <div class="mb-3"> <select class="custom-select center-block" name="stat" id="stat" placeholder="Status"> <option value="">Choose Status...</option> <option>A</option> <option>I</option> </select> </div> <div class="mb-3"> <!-- <a href="{% url 'customer_view' %}" class="btn … -
is there any way to convert this ajax call into django api?
This is my login code which was build elrier in ajax call now i want to make API end points for this so i converted this all into class view although this is not correct but i need some help when i am checking this with postman i m getting error this is not post request. i tried (self,request,args,krgws) but did not work class LoginAPIView(APIView): def login(request): """ dashboard login :param request: :return: """ logger.info("inside login") if request.user.is_authenticated() and request.user.is_superuser: return HttpResponseRedirect(reverse('activity:index')) if request.is_ajax(): username = request.POST.get('username', None) password = request.POST.get('password', None) if password is None or username is None: return JsonResponse({'status': 'failed'}) msg = {} try: user = authenticate(username=username, password=password) if User.objects.filter(username=username).exists() and user is not None: groups = Group.objects.all().values('name') check_group = lambda user_group, groups : any(ug in groups for ug in user_group) if (not user.groups or not check_group(user.groups.all().values("name"), groups)) and not user.is_superuser: return JsonResponse({"redirect_url" : "/"}) if user is not None: if user.is_active: auth_login(request, user) msg['status'] = 'ok' user_activity = {"email": user.email, "first_name": user.first_name, "last_name": user.last_name, "activity": 'logged in'} UserActivity.objects.create(**user_activity) else: msg['status'] = 'failed' else: msg['status'] = 'failed' except: msg['status'] = 'failed' return JsonResponse(msg) else: raise Http404('page not found.') -
How to solve admin.E040 in Django?
I have installed rest framework token authentication in Django and every time I run the local server it gives me an error. : (admin.E040) UserModelAdmin must define "search_fields", because it's referenced by TokenAdmin.autocomplete_fields. I -
I'm trying to use django login view and get NoReverseMatch error during rendering base template
Please, help! I'm really stuck, I'm trying to make login page using django login view and time after time I'm getting NoReverseMatch error on rendering base template. In the documentation I read about tag url, but I don't understand how to use it. Here is my base template <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8" /> <title></title> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="favicon.png" /> <link rel="stylesheet" href="libs/bootstrap/bootstrap-grid-3.3.1.min.css" /> <link rel="stylesheet" href="libs/font-awesome-4.2.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="libs/fancybox/jquery.fancybox.css" /> <link rel="stylesheet" href="libs/owl-carousel/owl.carousel.css" /> <link rel="stylesheet" href="libs/countdown/jquery.countdown.css" /> <link rel="stylesheet" href="css/fonts pariszanka.css" /> <link rel="stylesheet" href="css/media.css" /> </head> <style> *::-webkit-input-placeholder { color: #666; opacity: 1; } *:-moz-placeholder { color: #666; opacity: 1; } *::-moz-placeholder { color: #666; opacity: 1; } *:-ms-input-placeholder { color: #666; opacity: 1; } html { position: relative; min-height: 100%; } body { margin-bottom: 60px; background-color: #d7dad9; } .header{ font-family: IsadoraBold; text-align: center; font-size: 30px; } .top_line{ background-color: #24292E; color: white; } .bottom_line{ background-color: #24292E; color: white; } .top_name{ float: left; list-style-type: none; } .top_nav{ float: right; } .top_nav ul li{ list-style-type: none; display: inline-block; vertical-align: center; padding-right: 40px; } .top_nav a{ color: white; } .top_nav a:hover{ color: #78B0AE; } </style> <body> <div class="top_line"> … -
How to display several employees from mysql on the my index.html?
Code for index in views.py def index(request): employees = Employee.objects.all() schedules = [] for e in employees: s = Schedule.objects.filter(employee_id=e.employee_id, is_active=1) if (s.count() > 0): data = {} data['employee_id'] = e.employee_id data['schedule'] = s schedules.append(data) context = { "employees": employees, "schedules": schedules } print(request.user.username) return render(request, 'index.html', context) Hmtl of Index <div class="col-md-3 parent"> <div class="card card-profile"> <div class="card-avatar"> <a href="#pablo"> <img class="img" src="{% static 'img/faces/marc.jpg' %}"> </a> </div> <div class="card-body"> <h5 class="card-category text-gray">{{ employee.job_title.job_title }}</h5> <h4 class="card-title">{{ employee.first_name }} {{ employee.last_name }}</h4> <h6 class="card-category text-gray">ILO - {{ employee.employee_id }}</h6> <h6 class="card-category text-gray">HOME HEALTH</h6> <p class="card-description" style="font-weight:bold"> My problem is i have several employees on mysql database and i wanted to show those employees on the Index Page, right now only one employee showing up. Thanks if for the help. -
Django loop all existing record to save but only one record save
this is my code in html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr>{% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile-{{d.id}}" value="{{d.id}}" style="outline: none;" required/>{{d.id}}{{d.Description}}</td> <td></td> </tr> {% endfor %} what I tried in my views.py myfile = request.FILES['myfile-6'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() I don't have idea on how to loop this myfile = request.FILES['myfile-6'] with the existing id of Table Documents. please help me guys, im stuck on this problem 3days -
How to make "Group By" query in Django?
I'd like to make the query like this with Django ORM SELECT MAX(`product_item`.`order_value`) AS `max_order_value`, `product`.`title` AS `product_title`, `product`.`thumbnail_url` AS `product_thumbnail_url`, `product_item`.`title` AS `item_title` FROM `product_item` INNER JOIN `product` ON (`product_item`.`product_uid` = `product`.`product_uid`) WHERE ( `product_item`.`state` = 'SALE' AND `product_item`.`hidden` = 'N' AND `product_item`.`latest` = 1 AND `product`.`state` = 'SALE' AND `product`.`last_item_added_date` >= '2019-11-04 10:06:36.640586' AND `product`.`last_item_added_date` < '2019-11-04 10:26:36.640603' ) GROUP BY `product_item`.`product_uid`; And I tried some code below.. ProductItem.objects .filter( state="SALE", hidden="N", latest=1, product__state="SALE", product__last_item_added_date__gte=timezone.now() - timedelta(minutes=20), product__last_item_added_date__lt=timezone.now(), ) .values("product__product_uid") .annotate(max_order_value=Max("order_value")) .annotate( product_title=F("product__title"), product_thumbnail_url=F("product__thumbnail_url"), item_title=F("title"), ) .values( "max_order_value", "product_title", "product_thumbnail_url", "item_title", ) But I kept getting the result which group by with multiple fields that I wrote at last values() function call like this SELECT MAX(`product_item`.`order_value`) AS `max_order_value`, `product`.`title` AS `product_title`, `product`.`thumbnail_url` AS `product_thumbnail_url`, `product_item`.`title` AS `item_title` FROM `product_item` INNER JOIN `product` ON (`product_item`.`product_uid` = `product`.`product_uid`) WHERE ( `product_item`.`state` = 'SALE' AND `product_item`.`hidden` = 'N' AND `product_item`.`latest` = 1 AND `product`.`state` = 'SALE' AND `product`.`last_item_added_date` >= '2019-11-04 10:06:36.640586' AND `product`.`last_item_added_date` < '2019-11-04 10:26:36.640603' ) GROUP BY `product_item`.`product_uid`, product_title, `product`.`title`, `product`.`thumbnail_url`, `product_item`.`title`; How can I fix the orm code to make it work? Thank you -
Get return quote price
We have a quote model that holds details for a quotation and we generate a price based on the from and to location. But it gets messy when you want a return price. Here's the code: def get_price(quote): // do stuff with quote and return the quote object def auto_price(quote): quote = get_price(quote) return_quote = None if quote.is_return: return_quote = deepcopy(quote) return_quote.from = quote.to return_quote.from_place_id = quote.to_place_id return_quote.to= quote.from return_quote.to_place_id= quote.from_place_id return_quote = get_price(quote) I can manually add the values of return_quote in DjangoRest on create() but how do I access this later? There's no return_quote on the original model. Should I make return_quote a JSONField on the model? That will further make things complicated. -
Starting apps on mac with python and pycharm
so im trying to open an app on the terminal on my mac and it says /Users/tiga/PycharmProjects/Pyshop1/venv/bin/python3: can't open file 'manage.py': [Errno 2] No such file or directory what can I do? -
What is the best way to do a matrix style reporting in a Django App?
I have a number of transactions in my model: Transaction Date Category Amount 1 Jan Sales $1000 2 Feb Expense $500 3 Jan Expense $500 4 Mar Interest $100 What is the most efficient way to generate report in view.py that look like this? I know this is an easy questions but I'm curious what is the most efficient way to implement this matrix reporting? Category Jan Feb Mar Sales $1000 Expenses $500 $500 Interest $100 Total $500 -$500 $100 -
Listing foreign key object field in HttpResponse results
I apologize ahead of time, as I'm sure this question has been answered in full, but I must be missing a key component. I'm attempting to list a report's created_by user's first_name field in the existing results. From what I can tell, I have everything set up correctly, but only the Report object's attributes are rendering. In models.py, I have an object "Report" with an FK to the "User" object: created_by = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE) In views.py, I am creating the "reports" object using this: reports = Report.objects.order_by('-created_on').select_related('created_by').all() Running this in a django shell shows the SQL that I would expect, including the first_name field being pulled from auth_user.first_name: >>> print(Report.objects.order_by('-created_on').select_related('created_by').all().query) SELECT "report"."id", "report"."name", "report"."created_on", "report"."created_by_id", "report"."data_source", "report"."report_date", "report"."case_id", "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "report" INNER JOIN "auth_user" ON ("report"."created_by_id" = "auth_user"."id") ORDER BY "report"."created_on" DESC However, I must be doing something wrong in my HTML: {% for report in reports %} <tr> <td>{{ report.name }}</td> <td>{{ report.users.first_name }}</td> <td>{{ report.report_date }}</td> </tr> {% endfor %} I've attempted just about every variation of report.*.first_name that I can think of, but in each case, only the report.name and report.report_date values are coming through. I … -
Django Charfield Fixed Length Clean Error
I created a model I call FixedCharField, which is essentially a CharField that must contain a set number of chars, including whitespace. My implementation is built off of this example. I have a form that takes in a text file via upload, then the server reads the data and parses the various sections to populate my model's fields, programatically. This means that I am able to save instances of a model without using the admin form. This works great, however it does not work properly when I then try to open, then save the data within an admin form. It appears that the data to be cleaned is stripped of leading/trailing whitespace before being passed to the regex validator. I know it is stored with the whitespace because when I open the admin form, I see a 4-char field with the value 'A ' (that's an "A" with three spaces afterwards). However, I cannot save the page as it will throw the error message from my regex validator. If I print a repr() of the value argument of the clean function, it does not include whitespace, but is simply 'A'. Is there a way for me to change my model … -
How to search and show a pdf file inside a django app?
I have a Profile Model for add more fields for the User Model of django, one of the fields is a pdf file. I need to create a view for search the pdf and show in the browser. Here is my code: def resume_view(request): url_resume = request.user.profile.resume.url cd = os.getcwd() + '{}' dir_resume = cd.format(url_resume) with open(dir_resume, 'r') as pdf: response = HttpResponse(pdf.read(), mimetype='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response The problem is when I call the view I got this error: 'charmap' codec can't decode byte 0x81 in position 506: character maps to <undefined> I don't know if is important but is this the model profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) resume = models.FileField(upload_to=user_resume_path, null=False) How Can I Fixed? -
How to get all related data using django signal post_save and save it to another table
I just want that if the admin insert the Course(ABM) and Education Level (Grade 11) and Section(Chronicles) it will get all related data in subjectsectionteacher(second picture) and it will automatic save to student enrolled subject(third picture) my problem is only one data save. this is my code in models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,null=True) class SubjectSectionTeacher(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Employee_Users = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True) class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE, null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE, null=True,blank=True) @receiver(post_save, sender=StudentsEnrollmentRecord) def create(sender, instance, created, **kwargs): teachers = SubjectSectionTeacher.objects.all().filter(Sections=instance.Section,Education_Levels=instance.Education_Levels) if created and teachers.exists(): StudentsEnrolledSubject.objects.update_or_create( # This should be the instance not instance.Student_Users Students_Enrollment_Records=instance, # The below is also not an instance of SubjectSectionTeacher Subject_Section_Teacher=teachers.first()) I hope the title and the picture is enough to understand what im trying to say if not, im sorry! UPDATE this … -
uWSGI application handles HTTPS requests
I am writing a RESTful application using Django, and running it with uwsgi using following conf: ... socket = 127.0.0.1:8001 ... I am using Nginx with following conf # listen on 80 and 443 server { root /var/www/html; index index.html; server_name ...; location / { try_files $uri /index.html; } listen [::]:443 ssl ipv6only=on; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate ...; ssl_certificate_key ... include ... ssl_dhparam ... } server { listen 8000; server_name ...; location / { uwsgi_pass 127.0.0.1:8001; include uwsgi_params; } } server { if ($host = ...) { return 301 https://$host$request_uri; } # managed by Certbot listen 80 default_server; listen [::]:80 default_server; server_name ...; return 404; # managed by Certbot } And Nginx on port 80/443 is serving a front-end project that would make request to https://[site.url]:8000/, then the browser would throw errors like ERR_SSL_PROTOCOL_ERROR. While I try to visit https://[site.url]:8000, the browser tells me that "This site can’t provide a secure connection [site] sent an invalid response. ERR_SSL_PROTOCOL_ERROR" -
Adding multiple items to cart at once in django
Is it possible to know which item in your django model has been selected by a user based off of an html class change? I have data in a django model that is presented to a user in the form of a table, the user needs to select which items they would like to purchase from the list and then checkout. They will select all of the items they would like and then submit it rather than submitting them one-by-one like a conventional 'add to cart' system. I have Jquery that allows me to toggle the html class of each row in the table which selects and highlights the row on click, however i don't know how to translate that change in class into a function that django can use to identify which items that were displayed have been selected to be added to the cart. JQuery $("body").on('click','#food_table tbody tr',function() { $(this).toggleClass("highlight"); }); HTML to show table and highlight class <style media="screen"> .highlight { background-color: yellow; color: white; } </style> ...... <table class="table table table-borderless" id="food_table"> <thead> <tr> <th>ID</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody> {% for order in orders %} <tr> <td>{{ item.pk }}</td> <td>{{ item.Price }}</td> <td>{{ item.Description }}</td> … -
How to build a self destructing chat app server?
I'm making a chat app server with self destructing chat room feature. I have to reset the timer after the last chat, and when the timer runs out I have to blow up the chat room. The important thing is that I have to send push notifications to users when the chat room is gone, and to record the deletion time in the DB(PostgreSQL). I tried to use Redis' expire, but I'm not sure it is possible to implement the push service. I should also consider that my server must be able to scale out. Do you have any good ideas? Thank you very much. -
Google API not compatible with python Celery Tasks?
I have a django project, trying to execute some celery workers to perform a task in the background to update my model. I can execute basic tasks (add .delay()) to end of method in views. ) But can not execute google api calls. I can execute the google API calls if it is not a delayed task and it works perfectly and updates my models. Once I make a .delay() and add to celery queue as a task, I get the ssl error at bottom. Simple task that calls api and prints results: WORKS @task() def simple_api_call(): r1=requests.get('https://jsonplaceholder.typicode.com/todos/1') rj1=r1.json() print(rj1))] Simple task that calls GOOGLE(youtube) api and prints results: SSL error @task def google_api_call() r1=requests.get('https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2Creplies&allThreadsRelatedToChannelId=UCQMZZMfz0D1RueGzcYLd87Q&searchTerms=love&key=MYKEY') rj1=r1.json() print(rj1))] btw you can test out the google api/get the url for the get request here (just unselect the api and oauth: https://developers.google.com/youtube/v3/docs/commentThreads/list?apix_params=%7B%22part%22%3A%22snippet%2Creplies%22%2C%22allThreadsRelatedToChannelId%22%3A%22UCQMZZMfz0D1RueGzcYLd87Q%22%2C%22searchTerms%22%3A%22love%22%7D SSL error when worker executes the google api call. INFO/MainProcess] Received task: todo.tasks.update_comments[ae9bebfe-4b3c-46ec-b197-0ffa56847f30] [2019-10-31 05:33:52,652: ERROR/ForkPoolWorker-2] Task todo.tasks.update_comments[ae9bebfe-4b3c-46ec-b197-0ffa56847f30] raised unexpected: SSLError(MaxRetryError('HTTPSConnectionPool(host='www.googleapis.com', port=443): Max retries exceeded with url: /youtube/v3/commentThreads?part=replies%2Csnippet&allThreadsRelatedToChannelId=UC_EyncGJh2QuQHhcfuDWL6g&searchTerms=%23vi&maxResults=100&order=time&key=xxxmyapikey (Caused by SSLError(SSLError("bad handshake: SysCallError(54, 'ECONNRESET')")))')) Traceback (most recent call last): File "/Users/tylervanzo/Desktop/trydjango/lib/python3.7/site-packages/urllib3/contrib/pyopenssl.py", line 485, in wrap_socket cnx.do_handshake() File "/Users/tylervanzo/Desktop/trydjango/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1915, in do_handshake self._raise_ssl_error(self._ssl, result) File "/Users/tylervanzo/Desktop/trydjango/lib/python3.7/site-packages/OpenSSL/SSL.py", line 1639, in _raise_ssl_error raise … -
Edit an object based on an attribute's value in Django
I have a view called Edit, that edits an object. I want the user to only be able to edit it if it's unlocked, meaning, an attribute is called locked = BooleanField() and in the view, you first check whether the object is locked or not before proceeding. This is the edit function so far: @login_required def editdossier(request, pk): dossier = get_object_or_404(Dossier, id=pk) form = AddDossierForm(request.POST or None, instance = dossier) context = {'form': form} if form.is_valid(): dossier = form.save(commit= False) dossier.save() context = { 'form': form, 'dossiers': Dossier.objects.all() } return render(request, 'dashboard/home.html', context) else: context= {'form': form} return render(request,'dashboard/modifier_dossier.html' , context) And this is what I want to do: @login_required def editdossier(request, pk): dossier = get_object_or_404(Dossier, id=pk) # CHECK IF DOSSIER.LOCKED == FALSE: form = AddDossierForm(request.POST or None, instance = dossier) context = {'form': form} if form.is_valid(): dossier = form.save(commit= False) dossier.save() context = { 'form': form, 'dossiers': Dossier.objects.all() } return render(request, 'dashboard/home.html', context) else: context= {'form': form} return render(request,'dashboard/modifier_dossier.html' , context) I did the following check: if dossier.locked == false: proceed but the condition is not checked. I tried if dossier[0].locked == false but it shows an error saying the object is not indexable.