Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The 'header_image' attribute has no file associated with it
When I create a new post with a picture, everything is ok, but if I edit it, want to, for example, change the picture or delete, then this error appears here is models.py ` from django.db import models from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='#') #new def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)])` here is views.py ` from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' class BlogCreateView(CreateView): model = Post template_name = 'post_new.html' fields = ['title', 'author', 'body', 'header_image'] class BlogUpdateView(UpdateView): model = Post template_name = 'post_edit.html' fields = ['title', 'body', 'header_image'] class BlogDeleteView(DeleteView): model = Post template_name = 'post_delete.html' success_url = reverse_lazy('home') @property def image_url(self): """ Return self.photo.url if self.photo is not None, 'url' exist and has a value, else, return None. """ if self.image: return getattr(self.photo, 'url', None) return None` post_base.html `{% load static %} <html> <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" rel="stylesheet"> <link href="{% static 'css/base.css' %}" rel="stylesheet"> … -
Django - most efficient way to get context of model in selected language
Let's suppose we have Author and Book models and we want our end-users to be able to select language (EN/FR) for displaying information. We have added language suffix (_en, _fr) to the fields we want to be translated. class Author(models.Model): first_name_fr = models.CharField(max_length=60) first_name_en = models.CharField(max_length=60) last_name_fr = models.CharField(max_length=60) last_name_en = models.CharField(max_length=60) class Book(models.Model): title_fr = models.CharField(max_length=60) title_en = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) In my views.py, I know I can get current language using get_language() (imported from django.utils.translation). Being new to Django, I am looking for the most efficient way to pass translated context to templates using a ListView. What I thought is overriding the get_context_data method to keep only fields in selected language and remove their suffix. But that could be somewhat complex (assuming we have model relationships) and I am not sure it's in the right direction. What would be the best practice for this? -
Django - show images with src from python list
I am trying to show few images on my website, I've collected the sources of all of them in a list. In html file I've created a loop to iterate through each of them. HTML body : <body> <div class="content"> {% for output in outputs %} <h1> {{ output }} </h1> <img src="{% static '{{output}}' %}" alt="Mountains" style="width:100%"> <img src="{% static 'images/1.jpg' %}" alt="Mountains" style="width:100%"> {% endfor %} </div> </body> So, the thing is - I am able to show image "1.jpg" from "images" directory (so the problem is not due to static files). I've also checked that "output" has the right content. This is the output of my code : enter image description here And this is directory where I store my images : enter image description here please, let me know if you have any idea what should i do next. Any advise will be helpful. -
(haystack with elasticsearch) {{ result.object.get_absolute_url }} doesn't work( I have get_absolute_url() method )
I have elastichsearch and haystack. I can search, autocomplete works just fine but when I get my search results I can't follow any link, they point to the same page I am on. This is my models.py: class Product(TranslatableModel): translations = TranslatedFields( category = models.ForeignKey(Category, related_name = 'products', on_delete = models.CASCADE), name = models.CharField(max_length = 200, db_index = True), slug = models.SlugField(max_length = 200, db_index = True) ) # image = models.ImageField(upload_to = 'products/%Y/%m/%d/', blank = True) description = models.TextField(blank = True) price = models.DecimalField(max_digits = 10, decimal_places = 2) available = models.BooleanField(default = True) created = models.DateField(auto_now_add = True) updated = models.DateField(auto_now = True) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args = [self.id, self.slug]) This is my search_indexes.py: from haystack import indexes from . models import Product, ProductTranslation class IndexProduct(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) description = indexes.CharField(model_attr = 'description') def get_model(self): return Product class IndexProductTranslation(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document = True, use_template = True) name = indexes.CharField(model_attr = 'name') name_auto = indexes.EdgeNgramField(model_attr = 'name') def get_model(self): return ProductTranslation I tried get_absolute_url() method in the shell: >>> from shop.models import Product >>> p = Product.objects.latest('id') >>> p.get_absolute_url() '/uk/shop/10/test/detail/' It doesn't even have anything in the href attribute … -
Update queryset with dictionary values
I am writing custom List filter and inside filter call i have a Django queryset as below queryset =[qs1, qs2, qs3] queryset have a attribute Count_val = 0, UUID = (unique id) for all objects in queryset so lets say qs1 = {uuid: 123, count_val: 0} qs2 = {uuid: 456, count_val: 0} qs1 = {uuid: 789, count_val: 0} Also I have a dictionary like {uuid: count_val} example {123: 5, 456: 10 , 789: 15 } I want to update queryset attribute count_values for all objects before returning queryset as response Maybe annotate but how i pull each uuid for each value queryset=queryset.annotate(count_val = Case(When(uuid_in=dictionary.keys(), then=dictionary[uuid]), field_type=Integer)) ## not correct syntax just an example # inserting to new field is also fine #queryset.extra(value={count_val : dictionary[uuid]}) return queryset Thanks for help -
Django admin panel css not working as expected in digital ocean server
I am trying to deploy django project in digital ocean ,my site’s css is working perfectly but my admin panel css is not working good, the dashboard of the datbase window overrides my entry page always before few days it seems to be working good but now the css makes the whole page messy enter image description here enter image description here -
How to get data from firebase database in Django Framework?
I am new to Firebase database and python. I am trying to get data from Firebase database in Django framework. It gives me order dictionary.I want feedback from the database.enter code here import pyrebase config={ "apiKey": "AIzaSyBQ_Lx4HC9aaElDShvQUE7AxCeCExC2R88", "authDomain": "eventmanagementdatabase.firebaseapp.com", "databaseURL": "enter your firebase url here", "projectId": "eventmanagementdatabase", "storageBucket": "eventmanagementdatabase.appspot.com", "messagingSenderId": "62525256630", "appId": "1:62525256630:web:e8750943665ef765430717", "measurementId": "G-J2R75159BC" } firebase=pyrebase.initialize_app(config) auth =firebase.auth() database=firebase.database() def postsign(request): email=request.POST.get("email") passw=request.POST.get("pass") d=database.child('YogaFeedback').get().val()[enter image description here][2] try: user=auth.sign_in_with_email_and_password(email,passw) except: message="Invalid credentials" return render(request,"signIn.html",{"messg":message}) return render(request,"postsign.html",{"e":email,"feedback":d}) enter image description here enter image description here -
Refer an object that just after the current loop index in jinja
{% for i in posts %} {% if i.loop.index++.user == i.user %} <!-- Do something --> {% endif %} {% endfor %} posts is the variable that is being looped, it has a ForeignKey that is user. i.loop.index is evaluated as i.0, i.1, i.2 ..., I want the index just after the current loop index, if the index is i.0 I want i.1, to achieve that I am doing this {% if i.loop.index++.user %}, which should be evaluated to {% if i.1.user %} if 0 is the index. But it is not working Any help is highly appreciated! Thank you -
nginx API url https → http
Using nginx,AWS. javascript contains url as a variable. But the actual request url has been changed to https. Can't you just request it as it is in the variables? enter image description here -
Preventing race conditions when iterating through formset
I am a novice, I wrote a Django app over a year ago and it's been running ever since, however I have a problem with race conditions. I've read a few articles on Django race conditions but can't find a solution relating to formsets. My app has a web hook. My bank sends credit card transactions made on my card. My app lists the transactions which have not yet been imported (copied) into the financial journal table, lets me select which ledger they should go into, and then copies them over. It has to work this way as the bank lists the transactions in single entry format (one transaction, one line) whereas a proper financial book keeping app uses a more complex double entry format. The issue I have is that the copying is slow due to a large amount of logic needed, and if the import is triggered in another browser then transactions get copied over twice. The formset checks that the transactions are not yet imported as part of the is_valid() operation and then marks them as imported at the end. Whats' the best way to prevent race conditions here? def import_transactions(request): transactions = Transaction.objects.filter(imported=False) FormSet = modelformset_factory(Transaction, … -
Django auth_login giving Value error("cannot force an update in save() with no primary key.")
This Question is not similar to others who have answers. Recently I had changed my database engine to "Djongo" from "sqlite3". After finishing successful migrations and executing runserver command successfully, When I tried to log in Django admin I'm getting this error. Traceback Error: Environment: Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 3.1.7 Python Version: 3.9.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'map.apps.MapConfig', ] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "E:\atom_django\mapping\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\atom_django\mapping\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\contrib\admin\sites.py", line 410, in login return LoginView.as_view(**defaults)(request) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\contrib\auth\views.py", line 63, in dispatch return super().dispatch(request, *args, **kwargs) File "E:\atom_django\mapping\venv\lib\site-packages\django\views\generic\base.py", … -
How can I call a java script function from django html page?
Looking for help to call a java script function from a html page, I have no idea about java script. js function to be called window.purpose.postMessage({ type: 'collection' }, {accesstoken: '1234rr55r3'},'*'); my html page in which this js function needs to be called <!DOCTYPE html> <html> <head> <title>User Redirect</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body onload="document.frm1.submit()"> <form action="{{url}}" name="frm1" method="post"> <p>Please wait.......</p> <input type="hidden" name="customerName" value="{{postData.customerName}}" /> <input type="hidden" name="customerEmail" value="{{postData.customerEmail}}" /> <input type="hidden" name="customerPhone" value="{{postData.customerPhone}}" /> </form> </body> </html> -
I have getting a problem in django url when I am at url ...abc/pqr and I click on xyz than It is not getting to the ...xyz but ...abc/xyz
I am new to django and on this plateform so for now I dont know how to post a question here, but is someone see this please help. I am getting a problem in my project of college management system. I have try to add a assignment submition functionality in my project. In which a student will click on a assignment created by teacher which will land him to a page either submition page of assignment or if he already submitted that assignment than update or only showing information about that. ***this is my url file.*** urlpatterns = [... path('studentattendancereport', studentviews.student_attendance_report, name='studentattendancereport'), path('fetchstudentattendance', studentviews.fetch_student_attendance, name='fetchstudentattendance'), path('applyforleavestudent', studentviews.applyforleave, name='applyforleavestudent'), path('marksreportstudent', studentviews.marksreportstudent, name='marksreportstudent'), path('assignment', studentviews.assignments, name='assignment'), path('assignmentupload/<int:id>', studentviews.assignment_upload, name='assignmentupload'), ] ***this is my views.py*** def assignments(request): subject = Subject.objects.filter(course=Student.objects.get(admin=request.user.id).course) assignments = [] for s in subject: for a in Assignment.objects.filter(subject_id=s.id): assignments.append(a) context = {'assignments': assignments} return render(request, 'cmsapp/student/assignments.html', context) def assignment_upload(request, id): if request.method == 'POST': student_id = Student.objects.get(admin=request.user.id) assignment = Assignment.objects.get(id=id) assignment_file = request.FILES['assignment'] try: Student_Assignment.objects.create(assignment_id=assignment, student_id=student_id, document=assignment_file) messages.success(request, 'Assignment is submited successfully.') return redirect('assignment') except: messages.error(request, 'There is some problem, Please try again later.') return redirect('assignment') else: assignment = Assignment.objects.get(id=id) student_id = Student.objects.get(admin=request.user.id) assignment_report = Student_Assignment.objects.filter(assignment_id=assignment.id, student_id=student_id).first() if assignment_report: context … -
How to check if json data has empty value or not in django
I have created a CRUD application in Django. and want to know how I can check if the input JSON data is empty or not for example: I am getting a JSON input dictionary as {'firstname':'abc','lastname':'xyz','username':'abc@123','email':'abc@abc.com'} I want to check if username is not empty and email is not empty. I don't want a required field in model but to handle the JSON data. If the JSON input is not valid i.e if username and email is valid then save the data into database else give a warning 400. -
how to fix Pylance missingImports? cannot import my app.How to add extra paths in settings.json?
image image2 I cannot import my "todolist_app" in my "urls.py", I get the message "Import "todolist_app" could not be resolved Pylance(reportMissingImports)" the code in urls.py is from todolist_app import views from django.contrib import admin from django.urls import path urlpatterns = [ path('/', views.todolist, name='todolist') ] I don't know what the problem is. I'm new to coding. I tried to add path in settings.json { "python.pythonPath": "tmenv\\Scripts\\python.exe", "python.analysis.extraPaths": ["todolist_app","E:\Django Projects\Django_projects\\taskmate\\todolist_app"] } and I get an error "Invalid escape character in string.jsonc(261)" -
Django unable to send email behind nginx proxy
My django project sends email verification correctly till its not put behind nginx proxy, when i add a nginx proxy i am unable to send email, it sometimes sends as well sometimes it doesnt. it doesnt show any error in console Nginx config: upstream django { server unix://ucurs/ucurs.sock; # for a file socket } # configuration of the server server { # the port your site will be served on listen 7000; # the domain name it will serve for server_name 127.0.0.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /log { access_log off; error_log off; uwsgi_pass django; include /ucurs/uwsgi_params; } # Django media location /media { alias /ucurs/media; # your Django project's media files - amend as required } location /static { alias /ucurs/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /ucurs/uwsgi_params; # the uwsgi_params file you installed } } Django library used for sending email : https://pypi.org/project/django-email-verification/ Django email config EMAIL_FROM_ADDRESS = 'noreply@ucurs.com' EMAIL_MAIL_SUBJECT = 'Confirm your email' EMAIL_MAIL_HTML = 'mail_body.html' EMAIL_MAIL_PLAIN = 'mail_body.txt' EMAIL_TOKEN_LIFE … -
How can i get the id related to specfifc user in django
I am trying to get the saloon id related to specific employee. After the login employee can add the service, but my filter query show the error "Field 'id' expected a number but got <bound method MultiValueDict.get of <QueryDict: {}>>." i don't know how can i get the saloon id Model.py class SaloonRegister(models.Model): saloon_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() is_active = models.BooleanField(default=False) class SignUp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) contact_no = models.BigIntegerField() class Men(models.Model): saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Service = models.CharField(max_length=30) price = models.BigIntegerField() View.py class MenView(TemplateView): template_name = 'men.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): saloonId = SaloonRegister.objects.filter(signup__user__signup__saloon=self.request.GET.get) try: men = Men( saloon_id=saloonId, user_id=request.user, Service=self.request.POST.get('service'), price=self.request.POST.get('price') ) men.save() return redirect('saloonMenu') except Exception as e: return HttpResponse('failed{}'.format(e)) -
Django-Vue app: allow access from certain PCs only
I have a Django-DRF (backend) and Vue.js(frontend) web application. This application is for our company only and I want to allow access from certain PCs only. There are no static IPs, so I cant use a whilelist of IPs. What is the most appropriate solution in this case? -
how to delete objects from DB and Django API view with Javascript (Django REST Framework)
I'm using Django as backend, PostgresSQL as DB , and HTML, CSS, Javascript for frontend. I am using Djnago Rest Framework to show all the product in Cart and now I got stuck on to delete those specific product. I'm using Javascript to show all the detail of the product which is selected by user. Here is the code: views.py @api_view(['GET']) def showproduct(request): if request.method == 'GET': result = CartProduct.objects.all() serialize = productserializers(result, many = True) return Response(serialize.data) and now the javascript code which I'm calling the Django API index.html <script> $(document).ready(function() { $.ajax({ url: 'http://127.0.0.1:8000/index/showdata/', dataType: 'JSON', success: function(data){ for (var i = 0; i < data.length; i++) { var row = $('<tr><td style="font-style:bold">'+data[i].name+'</td><td style="font-style:bold">'+data[i].price+'</td><td><a href='+data[i].link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><a href="" class="btn btn-outline-danger"><i class="fas fa-trash"></i></a></td></tr>'); $("#table").append(row); } } }); }); </script> Now above code in index.html, there is a trash button where I want to add code to delete object from Django api and DB. How to do that? -
data given in the Ajax is not reaching in the views.py file and hence alert function is not working
I tried to reset password using Ajax in Django.For that, firstly I took email id from input box using a function and send it to views.py file using Ajax.In views.py file,there is a code for receiving email-id using GET method and check whether the email-id is available or not in the table.If available send the email-id back to html file using HttpResponse and display it using alert function.But it does not work properly.Can anyone suggest a solution for this. HTML file : <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title>Index Page</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link href="{% static 'styles/style.css' %}" rel="stylesheet"/> <script> function getpass(){ let username=$("#uname").val() $.ajax({ url : "{% url 'passwordreset' %}", type : "GET", data : {username : username}, success :function(data){ alert(data); } }) } </script> </head> <body> <section class="sflog" id="sflog"> <div class="container-fluid"> <div class="row"> <div class="col-12" id="std"> <form method="GET" action=""> {%csrf_token%} <center> <h3>Password <span>Reset</span></h3><br><br> </center> <div id="result"></div> <label style="color:white;padding-left:13%;">Enter Your Username</label> <center> <input type="text" id="uname" name="username" placeholder="Username" required><br> </center> <button type="submit" style="margin-left:12%;" onclick="getpass()" name="login">Submit</button><br><br><br><br> </form> </div> </div> </div> </section> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> urls.py from django.urls import path from . import views … -
gunicorn errors :gunicorn.service: Failed with result 'exit-code' and gunicorn.socket: Failed with result 'service-start-limit-hit'
As i am following through the tutorial of https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 gunicorn is not running when i used the command sudo systemctl status gunicorn my gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=developer Group=www-data WorkingDirectory=/home/developer/myprojectdir ExecStart=/home/developer/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bharathwajan.wsgi:application [Install] WantedBy=multi-user.target error comes when i try to check the status of gunicorn by the command sudo systemctl status gunicorn Error: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2021-06-04 03:53:42 UTC; 48min ago TriggeredBy: ● gunicorn.socket Main PID: 51351 (code=exited, status=1/FAILURE) Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: self.stop() Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: File "/home/developer/myprojectdir/myprojectenv/lib/python3.8/site-packages/gunicorn/arbiter.py> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: time.sleep(0.1) Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: File "/home/developer/myprojectdir/myprojectenv/lib/python3.8/site-packages/gunicorn/arbiter.py> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: self.reap_workers() Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: File "/home/developer/myprojectdir/myprojectenv/lib/python3.8/site-packages/gunicorn/arbiter.py> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 gunicorn[51351]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jun 04 03:53:42 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: gunicorn.service: Failed with result 'exit-code'. lines 1-16/16 (END) when i tried sudo journelctl -u gunicorn.socket Logs begin at … -
Reloading a <div> element in Django but no refresh happening
I'm adding objects to my array list from a bar code scanner. The data is added after every scan of the barcode scanner it depends on how fast the user is in scanning. To display this data I have created a page. I don't want the whole page to refresh but that specific div that should display the scanned codes. This is what I have done so far urls.py path('status', include('detect_barcodes.urls')), views.py: @ms_identity_web.login_required def detect(request): stream = CameraStream() success, frame = stream.camera.read() if success: status = True else: status = False bar_codes = stream.used_codes data = (",\n".join(bar_codes)) return render(request, 'detect_barcodes/detect.html', context={'data': data, 'cam_status': status}) template file(detect.html):(I want to auto-refresh just the div with id="container") <div class="main-wrap"> <div class="container"> {% if cam_status %} <img src="{% url 'camera_feed' %}" style="width: 640px; height: 480px;"/> {% else %} <h3>Camera stream status: Camera is either not accessible or busy</h3> <h5>Things to check:</h5> <ul class="text-right list-inline"> <li>USB connection?</li> <li>Camera number in your .env file?</li> <li>Camera is already in use?</li> </ul> {% endif %} </div> <div class="container" id="container"> <form action="/submit/" method="post"> {% csrf_token %} Fill the Detail: <br/> <textarea id="description" rows="17" cols="90" name="description" class="myForm"> {{ data }} </textarea> <input type="submit" value="submit"/> </form> </div> </div> When I run … -
django-login-required middleware giving type error
In my django project I am trying to use the django-login-required-middleware. Upon running the server, I get the following error message: TypeError at / 'bool' object is not callable Traceback (most recent call last): File "/home/krishnan/anaconda3/envs/django_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/krishnan/anaconda3/envs/django_env/lib/python3.8/site-packages/login_required/middleware.py", line 26, in __call__ is_authenticated = request.user.is_authenticated() Exception Type: TypeError at / Exception Value: 'bool' object is not callable When I go to line 26 of the file site_packages/login_required/middleware.py, I see the following code: # Django v2 now has request.user.is_authenticated as a boolean instead # of a function that returns a boolean if django.VERSION[0] == 2: is_authenticated = request.user.is_authenticated else: is_authenticated = request.user.is_authenticated() I am using Django 3.1.6. I installed the middleware on 04 June 2021 with pip as instructed in the pypi page, and I presume it is the latest version(the middleware.py file does not show version info). As per the pypi page the middleware version is 0.6.1 and supports Django 3.0 also. But from the above code snippet, it would seem that the middleware code checks only for Django version 2 to use the is_authenticated property instead of the is_authenticated() function, and could be the reason for the error. Am I correct? Or … -
Celery Argument Passed Incorrectly
When I was trying to pass a string as an argument into my celery file, this error occurred: celery.beat.SchedulingError: Couldn't apply scheduled task add-every-10-seconds: get_data() takes 1 positional argument but 138 were given However, I can't quite figure out why this means -- I passed in the argument as a string, but somehow, Celery converts it into a char array or something. |-- data |-- tasks.py |-- nttracker |-- celery.py |-- manage.py nttracker\celery.py from __future__ import absolute_import app = Celery('nttracker', broker='amqp://', backend='rpc://', include=['nttracker.tasks']) app.autodiscover_tasks() app.conf.update( timezone = "Asia/Taipei", result_backend = 'django-db', broker_url = 'redis://127.0.0.1:6379', cache_backend = 'default', beat_schedule = { 'test': { 'task': 'data.tasks.get_data', 'schedule': 10.0, 'args': "https://gist.githubusercontent.com/crimsonpython24/8a42e1c7226b73d59dcb2447fa961caa/raw/57441c0912cf51695b113745052c4829459dec02/test.json" }, } ) if __name__ == '__main__': app.start() data\celery.py from __future__ import absolute_import import django django.setup() import requests from celery import Celery from celery.schedules import crontab app = Celery() @app.task def get_data(url): r = requests.get(url=url) data = r.json() print(data) Can anyone please help? Many thanks in advance. -
Going through in a loop with random float values via next and previous button?
my model: class Comics(models.Model): comic_english_name = models.CharField(unique=True, max_length=250, verbose_name='English Name') class Comic_banks(models.Model): comic_english_name = models.ForeignKey(Comics, on_delete=models.DO_NOTHING) comic_chapter = models.FloatField(verbose_name='Comic Chapter No.') my view: def chapter(request, myid, chid): comic = get_object_or_404(Comics, id=myid) # passed current comic chapter_max = Comic_banks.objects.filter(comic_english_name=comic.id).aggregate(Max('comic_chapter')) #max or last chapter chapter_min = Comic_banks.objects.filter(comic_english_name=comic.id).aggregate(Min('comic_chapter')) # min or first chapter comicbank = Comic_banks.objects.filter(comic_english_name=comic.id, comic_chapter=chid) #chapter list with different comics my template code: {% load mathfilters %} <!-- Chapter link section Start --> <!-- Previous button Start --> <div class="flex-containerchapter"> {% for comicbank in comicbank %} {% if comicbank.comic_chapter <= chapter_min.comic_chapter__min %} <!-- if current chapter is below than First or minimum chapter then no previous button --> {% else %} <a class="btn but1" href='/comic/comicview/{{ comic.id }}/{{ comicbank.comic_chapter|floatformat:1|mul:10|sub:1|div:10}}/chapter'>Prev</a> <!-- it will subtract 0.1 in the previous value of chapter from chapter list --> {% endif %} {% endfor %} <!-- Previous button end --> <!-- Next button Start --> {% for comicbank in comicbank %} {% if comicbank.comic_chapter == m.comic_chapter__max %} <!-- if current chapter is above than last or maximum chapter then no next button --> {% else %} <a class="btn but1" href='/comic/comicview/{{ comic.id }}/{{ comicbank.comic_chapter|floatformat:1|mul:10|addition:1|div:10}}/chapter'>Prev</a> <!-- it will add 0.1 in the next value of chapter from chapter list …