Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dots (coordinates) on a static map
I would like to display a dots on the static map ( taken from database ) result would look something like: there are latitude and longtitude data in my database for each object that i would like to display. The question is: is this only possible by using some kind of google API? or this could be done in some other way? Maybe somebody seen something similar and would give me a hint where to start? Update: I've gone so far that the only thing is to convert html object to js array. Any idea how to? Html:: {% for c in object_list %} JS:: var flights = {% for c in object_list %} <<--- convert to js.. -
Show S3 SSE-C Encrypted Image using Presigned URL in the browser
Without any encryption, even for a file that resides in a bucket with no public access, I can create a presigned URL by modifying response-content-type header for an image with an expiry time and it would show the image in the browser. This is very helpful when I need to display the image in the browser using the src attribute of img HTML tag. However, When I encrypt an image using SSE-C in S3, is there any way to show the image in the browser using presigned URL? I've some images which are encrypted using SSE-C in S3. However, in some cases they might required to be shown in the browser. The documentation states this aws docs link Is there any way? Thank you. -
How to display one questions at one page in django template?
I am creating a mcqs based app where I have to create display one questions on each page and when the users answers that question I want to redirect it to next question, but I am quite confused how to apply this logic? I am getting all the questions in questions = Question.objects.all() this is my templates file <div class="container"> <div class="text-danget mt-3"> <h3>Simple Js/Python App</h3> <hr> <table> {% for i in questions %} <tr> <td class="text-primary">{{forloop.counter }}) {{i.question_text}}</td> </tr> {% for j in i.get_answers %} <tr> <td> <input type="radio" class="rb"> {{j.options}}</td> </tr> {% endfor %} {% endfor %} </table> </div> </div> -
Deploy web app using Django, Nginx and Gunicorn in Ubuntu 20.04
I have developed a web application with Django and I am trying to publish it in a virtual machine created with Azure. As this is a test server, I have not yet purchased a domain or a SSL certificate and I would like the application to be accessible at http://XX.XX.XX.XX address (where XX.XX.XX.XX is the public IP of the server). To do that I'm using the following software stack: Ubuntu (20.04) Django (3.0.7) Virtualenv (20.0.17) Gunicorn (20.1.0) Nginx (1.18.0) To deploy the app I followed that guide: https://arctype.com/blog/install-django-ubuntu/ This is my /etc/systemd/system/gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target This is my /etc/systemd/system/gunicorn.socket: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/myapps/djangoapp/ ExecStart=/home/myuser/myapps/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock djangoapp.wsgi:application [Install] WantedBy=multi-user.target This is my /etc/nginx/conf.d/django.conf: server { listen 80; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myuser/myapps/djangoapp/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The systemctl status gunicorn.socket statement returns the following: ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Thu 2022-03-10 08:57:02 UTC; 1h 21min ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) Tasks: 0 (limit: 9536) Memory: 0B CGroup: /system.slice/gunicorn.socket Mar … -
Serve django media files throw nginx
I work with django rest application in backend, I run it as socket service, it's published by nginx, I've a CORS error when I try to access to media files. server { listen 8000; server_name $host; access_log /var/log/nginx/backend.access.log; error_log /var/log/nginx/backend.error.log; location /media/ { alias /home/ouassim/Sources/app/backend/documents/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Firing the post_save signal in a defined manner
I am working on a django application. I have a process flow in which I have steps and their respective status. I have a model for steps. Below is my flow diagram As soon as the status of step 1 changes to complete, status of all the following steps gets updates. I wrote a post_save signal for the status change of the steps. @receiver(post_save, sender=WorkflowStep) def updateWorkflowStep(sender, instance, created, **kwargs): # updated step 2, step 5, and step 8 statuses Problem: As soon as I will update the status of step "2", the post_save signal will get triggered and update the status of Step "3", followed by step "4". So my. step "5" and step "8" will never get updated as by the time code could update their status, post_save again got triggered because of step "2" status change. How can I make sure that all the three branches gets updated in sequence. Say first step 2, step 3 and step 4 gets updated. Then step 5, 6, and 7. And then step 8, 9, and 10. -
How to properly notify client of changed status?
I am writing a (Django-based) website which is working just fine. It displays a list of sensors and their status. If a new sensor is attached, the user needs to wait for a certain amount of time until it is warmed up and ready to use. Also, when the sensors are updated (which the user can trigger, but can also be done automatically by the system) - the user needs to wait. On the server side I have all signals/Status updates/whatsoever available. Now I want to create an overlay for the current webpage where the statuschange is displayed for x seconds and userinput is disabled. I have no clue what technology to use. I could frequently ask for updates client -> server but that doesn't feel like the correct way. Any suggestions on what to search for? No code here because the answer is probably independed of my website code -
I can't get all product from page website ( scraping aliexpress using pyhon selenium)
I am trying to web scrape Aliexpress using Selenium and Python, and everything seems to be okay. The issue I have ran into is that my code scrape only and exactly 10 products from each page instead of all the products, and I still don't know the reason behind it. Also, I want a method to scrape the links of each product in order to extract reviews and comments. Here is my code : from selenium import webdriver from lxml import html from time import sleep from itertools import zip_longest import csv driver = webdriver.Edge(executable_path=r"C:/Users/OUISSAL/Desktop/wscraping/XEW/scraping/codes/msedgedriver") with open ("data.csv", "w", encoding="utf-8") as csvfile: wr = csv.writer(csvfile) wr.writerow(["Title","Price", "Currency", "Reviews", "Number of orders"]) for page_nb in range (1,4): driver.get('https://www.aliexpress.com/wholesale?trafficChannel=main&d=y&CatId=0&SearchText=bluetooth+earphones&ltype=wholesale&SortType=default&page={}'.format(page_nb)) sleep(1) tree = html.fromstring(driver.page_source) driver.execute_script('window.scrollTo(0, document.body.scrollHeight);') sleep(10) for product_tree in tree.xpath('/html/body/div[3]/div/div/div[2]/div[2]/div/div[2]'): title = product_tree.xpath('.//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[1]/h1/text()') price = product_tree.xpath('.//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[2]/span[2]/text()') currency = product_tree.xpath('.//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[2]/span[1]/text()') review = product_tree.xpath('.//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[4]/span[2]/text()') nb_sold = product_tree.xpath('.//*[@id="root"]/div/div/div[2]/div[2]/div/div[2]//div[2]/div[4]/span[1]/text()') list = [title, price, currency, review, nb_sold] exported = zip_longest(*list) wr.writerows(exported) print(list) driver.close() Thank you ! -
Access value of row using Django's Case/When queryset conditions
I'm trying to migrate some value in Django, I'm using the Django model's When-Case. My implementation is simple, it worked with static string: When( description__in=pre_desc, then=Value("pre-string"), ), When( description__in=post_desc, then=Value("some-post-string"), ) This code above works. But the problem arises when I try to add something before or after to existing string: pre_desc = ["a", "b", "c"] post_desc = ["a", "b", "c"] StoreO.objects.filter().update( description=Case( When( description__in=pre_desc, then=Value("pre-string"+description), ), When( description__in=post_desc, then=Value(description+"some-post-string"), ), default=Value("def_str")), ) ) It says, description is not defined. Can anyone give me some workaround? I also tried str(F('description')+'randomstr') which resulted in F('description')+'randomstr' in the db. -
utiliser une méthode django dans angular
BOnjour, pour les cours je créer une application angular. je dois aller chercher mes pizzas dans la base de données depuis pizza commande (pizzaitem) qui est lié à une commande. Ma méthode django, je ne sais pas si elle marche: @action(detail=False, methods=["GET"]) def getPizzaById(pizzaId): pizza = PizzaSerializer.objects.filter(pizzaId = id).get() return pizza et l'utilisation dans angular: {{pizzaCommande.getPizzaById(pizzaCommande.pizzaId).name}} je ne sais comment l'implémenter PS: je débute soyer gentil -
How Can I set environment variables on AWS EC2?
I am working on a Django application to be hosted on AWS EC2. Some of my variables are sensitive and have to be excluded from version control. Some are not sensitive but the values vary from environment to environment. To achieve this, I am saving the values in the environment and accessing via the code. CircleCI provides a way of achieving this by Environment Variables of the project. Heroku also provides similar functionality. Please how can I set these variables in AWS Ec2? -
New row in Django text field
In my Django app I have: models.py content_don = models.TextField() I write content into that field and then save it with 'Submit'. Problem is, on my page I preview it with: post.html <p class="article-content mt-3 mb-1"><strong>Description: </strong></p> <div class="media content-section mt-1 mb-1"> <p class="lead">{{ post.content_don }}</p> </div> All content is in the same row. There are now rows which I typed in when I wrote text during form input. Why is that? -
Django - Get database records for last 7 days
I am trying the retrieve the last 7 days of records from my SQLite database. I have an attendance system and I am trying to display some statistics on the UI, however currently it is not working - I will display my current code for this below. Models: class Meta: model = User fields = ("username", 'email', 'password1', 'password2') class is_Present(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=datetime.date.today) is_present = models.BooleanField(default=False) class clocked_Time(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(default=datetime.date.today) time = models.DateTimeField(null=True, blank=True) signed_out = models.BooleanField(default=False) Views.py: # Get Count of Present Employees in last week def present_week_employees(): today = date.today() week = today - timedelta(days=7) present_employees_all = is_Present.objects.filter(date=week).filter(is_present=True) return len(present_employees_all) # Displays admin attendance portal functions def attendance_portal(request): if not request.user.is_authenticated: messages.warning(request, f'Please sign in to mark attendance out') return redirect('login') elif not request.user.is_superuser or not request.user.is_staff: messages.warning(request, f'Must be admin to access this feature') return redirect('home') elif request.user.is_superuser: count_employees_all = count_employees() # shows count of employees present_employee_all = present_employees() # shows count present employees today present_employee_all_week = present_week_employees() # shows count present employees in last 7 days # Gets the employees present today/week today = datetime.today() week = today - timedelta(days=7) # Gets employees displayed and paginated … -
in django how to output table data to html template?
I have created model, write views, and urls and html template file but can't show data when doing. If you know the reason please help me? this is 3 file in django project models.py # from django.contrib.auth.models import User from django.contrib.auth.models import User from django.db import models # from rest_framework.authtoken.admin import User from schedule import settings class GiaoVien(models.Model): madotxep = models.ForeignKey(DotXep, on_delete=models.CASCADE) hodem = models.CharField(default='', max_length=50) ten = models.CharField(default='', max_length=20) viettat = models.CharField(default='', max_length=20) nhomgv = models.CharField(default='', max_length=20) mamau = models.IntegerField(default=0) stt = models.IntegerField(default=0) ghichu = models.TextField(default='') def __str__(self): return str(self.id) views.py enter code here from django.shortcuts import render, redirect from inputdata.models import GiaoVien def show(request): queryset = GiaoVien.objects.all() context= {'clientes': queryset} return render(request, "Main/showdata.html", context) showdata.html {% extends 'base.html' %} {% block title %}Show Giao Vien{% endblock %} {% block content %} <table> <thead> {% for field in clientes %} <th>{{ field.label }}</th> {% endfor %} </thead> <tbody> <tr> {% for field in clientes %} <td>{{ field.value|default_if_none:'' }}</td> {% endfor %} </tr> </tbody> </table> {% endblock content %} -
Django + VueJS3 app: remove the Hashtag(#) from url
Here is a tricky situation. I'm working on a Django project on top of which VueJS CDN is used for one application's render. It goes like www.mywebsite.com/newapp where the new app only is rendered with VueJS. The linked are handled by Vue router on a basic configuration: // Routess // let routes = [ { path: '/', name: 'home', component: home, meta: { scrollPos: { top: 140, left: 0 }, }, }, { path: '/about', name: 'about', component: about, meta: { scrollPos: { top: 140, left: 0 }, }, }, ]; const scrollBehavior = (to, from, savedPosition) => { if (to.hash) { return { el: to.hash }; } return to.meta?.scrollPos || { top: 140, left: 0 }; }; const router = VueRouter.createRouter({ history: VueRouter.createWebHashHistory(), scrollBehavior, routes, }); const app = Vue.createApp({ data() { return { } }, }); const vm = app.use(router).mount('#app'); So I get this url link with a hashtag: www.mywebsite.com/newapp/#/ www.mywebsite.com/newapp/#/about/ on a nested component, It will just be like When I use only router history like: const router = VueRouter.createRouter({ history: createWebHistory(), scrollBehavior, routes, }); Then I get www.mywebsite.com/home But I do need to have to static url. It doesn't seemed to be a proper way to … -
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this
Free dyno hours quota remaining this month: 549h 42m (99%) Free dyno usage for this app: 0h 17m (0%) For more information on dyno sleeping and how to upgrade, see: https://devcenter.heroku.com/articles/dyno-sleeping No dynos on ⬢ junfenggege -
Django with super and Init
I dont understand this code. I'm watching couple of tutorial for python/django tutorial. Hope you guys can enlighten me. class ProfileForm(ModelForm): class Meta: model = Profile fields = ['name', 'email', 'username', 'location', 'bio', 'short_intro', 'profile_image', 'social_github', 'social_linkedin', 'social_twitter', 'social_youtube', 'social_website'] def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) what does this code do? def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) Thanks -
How to solve 404 response redirect error?
I created two handler functions in my Django project for 404 and 500 errors. I want to redirect the user to the homepage if this page does not exist. So I write these codes. But when I enter the website it says: This page isn’t working. domain.com redirected you too many times. urls.py handler404 = handler404 handler500 = handler500 views.py def handler404(request, exception=None): return redirect('/') def handler500(request, exception=None): return redirect('/') settings.py: DEBUG = false Where is my mistake and how can I solve it? If I delete handlers in urls.py, errors will be remove and returns normal. -
How to solve domain.com redirected you too many times error? [closed]
I created two handler functions in my Django project for 404 and 500 errors. But when I enters the website it says: This page isn’t working. domain.com redirected you too many times. urls.py handler404 = handler404 handler500 = handler500 views.py def handler404(request, exception=None): return redirect('/') def handler500(request, exception=None): return redirect('/') settings.py: DEBUG = false Where is my mistake and how can I solve it? -
Unable to send the request to django views using xmlhttprequest
I am doing one application .In that i created the register function in Django views, and in html page, created form and trying to submit it with XMLHTTPRequest.But when i hit the submit button, total form data appending to url and not hitting the Django views register function.Below is the my function to submit the form. function submitForm(oFormElement) { // alert('called'); var xhr = new XMLHttpRequest(); xhr.onload = function(){ alert(xhr.responseText); } xhr.open("POST","/site/register/",true); xhr.setRequestHeader("X-CSRFToken", csrftoken); alert('called'); xhr.setRequestHeader('Authorization', 'Bearer ' + token); xhr.send(); alert('called') return false; } And if i mention the form details in send() also like below also same happening, total headers and data appending to url and not hit the Django Views method. function submitForm(oFormElement) { // alert('called'); var xhr = new XMLHttpRequest(); xhr.onload = function(){ alert(xhr.responseText); } xhr.open("POST","/site/register/",true); xhr.setRequestHeader("X-CSRFToken", csrftoken); alert('called'); xhr.setRequestHeader('Authorization', 'Bearer ' + token); xhr.send(new FormData(oFormElement)); alert('called') return false; } So please help me, how to hit the django views function when i submit the form from HTMl page. -
ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'
I use translation in my Django apps. Since I installed Django version 4, when I try to import ugettexget_lazy as shown in the code below from django.utils.translation import ugettexget_lazy as _ I get the following error: ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' -
How to generate aware time object in Faker?
I have the following (simplified) model and factory: models.py class Event(): duration = FloatField() start_time = TimeField() finish_time = DateTimeField() def save(self, *args, **kwargs): self.finish_time = self.start_time + timedelta(hours=self.duration) event_factory.py from factory import Faker class EventFactory: date = Faker( "date_time_this_month", before_now=False, after_now=True, tzinfo=timezone.get_current_timezone(), ) start_time = Faker("time_object") duration = Faker("random_int") However, my save method raises Warning: DateTimeField Event.finish_time received a naive datetime (2022-03-28 12:43:38) while time zone support is active. date is aware due to tzinfo argument, but start_time is naive (I checked with django's timezone.is_aware()), because time providers in Faker do not seem to allow any timezone parameters. Any suggestion in getting a fake aware time object in factory-boy/Faker? -
Custom setting model does not apply until server restarted in django
I'm trying custom setting model to change some settings from admin. class Setting(models.Model): is_duel_cart_allowed = models.BooleanField(default=True) free_cancellation_duration = models.DurationField(default="0:0:0") return_order_duration = models.DurationField(default="0:0:0") is_return_charges_deducted = models.BooleanField(_("Return charges applied when order is returned"),default=True) is_shipping_charges_deducted_on_return = models.BooleanField(_("Deduct shipping charges when order is returned"),default=True) is_product_cancellation_charge_deducted = models.BooleanField(_("Cancellation Charges deducted when product is cancelled"), default=True) is_shipping_charges_deducted_on_cancel = models.BooleanField(_("Deduct shipping charges when order is cancelled"), default=True) This is my model and when I turn ON/OFF any of these boolean fields, settings will remain unchanged until server is restarted. How to tackle this problem? Here is my view function code where I'm checking for these models changes from core.models import Setting setting = Setting.objects.first() class ReturnOrderViewset(viewsets.ModelViewSet): serializer_class = OrderSerializer def get_queryset(self): queryset = Order.objects.prefetch_related('items', 'items__product', 'items__user').filter(status_id=12) return queryset def create(self, request, *args, **kwargs): order = request.POST.get('order_id') return_reason = request.POST.get('return_reason') current_time = timezone.now() return_order_duration = setting.return_order_duration try: order = Order.objects.get(id=int(order)) return_reason = ReturnReason.objects.get(id=int(return_reason)) except Order.DoesNotExist: return Response({'message': 'Order not found'}, status=status.HTTP_404_NOT_FOUND) except ReturnReason.DoesNotExist: return Response({'message': 'Order not found'}, status=status.HTTP_404_NOT_FOUND) exp_time = order.created + return_order_duration print(order.created, exp_time) if order.status_id == 8: print("status is complete ======") if exp_time > current_time: print("exp time is great than current time") if all(item.product.is_return_allowed for item in order.items.all()): print("All products are return allowed =====") deductions … -
Cross origin request blocked for s3
I have my pre-assigned URL and policy (created on django) for object to be uploaded into S3 directly from JavaScript. It works as expected during development and in local server. as soon as I upload to host and server online it give me the error of cross origin request blocked on Firefox and on chrome, it says that the request has been aborted. I have allowed all the domains to on bucket as well. I have even put the bucket public. below is my bucket policy and cors policy. I would be so happy for find a solution for this. Bucket Policy { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1621532678577", "Effect": "Allow", "Principal": "*", "Action": [ "s3:PutObject", "s3:GetObjectAcl", "s3:GetObject", "s3:ListBucket", "s3:DeleteObject", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::[bucketname]/*", "arn:aws:s3:::[bucket-name]" ] } Cross-origin resource sharing (CORS) [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "PUT", "HEAD", "POST", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [ "x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2" ] } JavaScript function // auto-upload on file input change. $(document).on('change','.cfeproj-upload-file', function(event){ var selectedFiles = $(this).prop('files'); formItem = $(this).parent() $.each(selectedFiles, function(index, item){ var myFile = verifyFileIsImageMovieAudio(item) if (myFile){ uploadFile(myFile) } else { alert("invalid file chosen.") } }) $(this).val(''); }) function constructFormPolicyData(policyData, fileItem) { var contentType … -
Why not all showing up in vs code django/python intellisense
Hi I am new to Python/django and am using VS Code. Now I got python IntelliSense and pylance extension installed and most things are showing up on IntelliSense but some aren't. How can I get it to work for everything? I would very much appreciate some insight since it's driving me nuts... request.POST from an imported lib not showing up selected_meetup.participants not showing up nor is selected_meetup.participants.add from urllib import request from django.forms import SlugField from django.shortcuts import render from .models import Meetup from .forms import RegistrationForm # from django.http import HttpResponse # Create your views here. def index(request): meetups = Meetup.objects.all() return render(request, 'meetups/index.html', { 'meetups': meetups }) def meetup_details(request, meetup_slug): try: selected_meetup = Meetup.objects.get(slug=meetup_slug) if request == 'GET': registration_form = RegistrationForm() else: registration_form = RegistrationForm(request.POST) registration_form = RegistrationForm(request.) if registration_form.is_valid(): participant = registration_form.save() selected_meetup.participants.add(participant) return render(request, 'meetups/meetup-detail.html', { 'meetup_found': True, 'meetup': selected_meetup, 'form': registration_form }) except Exception as exc: return render(request, 'meetups/meetup-detail.html', {'meetup_found': False })