Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django custom widget: how to access field error?
I try to have more control over form rendrering and template. Initially, I used django-crispy but event if Layout give huge range of customization I thought it became confused... So I truned out to widget customization following django documentation and this site https://www.webforefront.com/. I first face issue with renderding field label. I fix that by passing label argument in attrs of CustomWidget but not sure it is a good practice. But my main issue is rendering erros... How can I manage this? template for input CustumoInput.html <div class="row mb-0"> <div class="input-group input-group-sm col-6 rounded"> <label>{{ widget.label }}</label> </div> <div class="input-group input-group-sm mb-1 col-2"> <input type="{{ widget.type }}" name="{{ widget.name }}" id="id_{{ widget.name }}" class = "textinput textInput form-control" {% if widget.value != None %} value="{{ widget.value }}" {% endif %} {% include "django/forms/widgets/attrs.html" %} /> {% for error in widget.errors %} <div class="invalid-feedback">{{ error }}</div> {% endfor %} </div> </div> widgets.py from django import forms class custom_input(forms.widgets.Input): template_name = 'ecrf/CustomInput.html' input_type = 'text' def __init__(self, attrs={}): super(custom_input, self).__init__(attrs) def get_context(self, name, value, attrs): context = super(custom_input, self).get_context(name, value, attrs) context['widget']['label'] = self.attrs['label'] context['widget']['attrs']['placeholder'] = self.attrs['placeholder'] context['widget']['attrs']['autocomplete'] = self.attrs['autocomplete'] context['widget']['attrs']['data-mask'] = self.attrs['data-mask'] return context forms.py self.fields['inc_tai'] = forms.IntegerField(label = 'Taille (mesurée … -
Error when i try to load mysqldb for jupyter notebook or python shell
Since i changed the connection to a mysql db, i get a error of mysql django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. this is my conf: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myophio_dev', 'USER': 'root', 'PASSWORD': 'password', 'HOST': '192.168.1.84', 'PORT': '113' } } In mysql workbench i can access the data. So, I don't know what is wrong. I am using a macOS 11. Can you help me? Python version: 3.10.2 also, i already did brew install mysql and brew reinstall mysql, brew restart services mysql I dont know what else I can do. -
Filter A foreignkey child model instance in a form field based on the parent value selected in another field in the same field
I would enter image description herelike to list getionnaire in the Projetform based on departement chosen in the another field of the same. -
Django User model with same fields
I saw tutorial on how to extend django model by giving 1-to-1 relationship to the django user model. My question is, if we have same fields on both User and profile(extend from user) model i.e email and username. When the user register on our site using User model, does the profile model will inherit the same username and email from User model? from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) -
Modifying django-allauth error messages on a signup form
I'm currently building a website that makes use of django-allauth and I've come across a problem regarding error messages while using a custom User model. My custom User model is called CustomUser, I've noticed that when django-allauth handles errors regarding the username, it uses the name of the user model as the starting word to the error message's sentence. Example image is linked below. Image of the error message How can I change this error message? I'd like to stay away from overriding any django-allauth views if possible, though I'd be happy with any solution! This is my Django form code that makes use of django-crispy-forms: <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} <div class="row"> <div class="col-12 col-lg-7"> {{ form.email|attr:"autofocus"|as_crispy_field }} </div> <div class="col-12 col-lg-5"> {{ form.username|as_crispy_field }} </div> <div class="col-6 col-lg-4"> {{ form.first_name|as_crispy_field }} </div> <div class="col-6 col-lg-4"> {{ form.last_name|as_crispy_field }} </div> <div class="col-12 col-lg-4"> {{ form.birthday|as_crispy_field }} </div> <div class="col-12 col-sm-6"> {{ form.password1|as_crispy_field }} </div> <div class="col-12 col-sm-6"> {{ form.password2|as_crispy_field }} </div> <div class="col-12 text-center"> {{ form.captcha|as_crispy_field }} {% for error in form.captcha.errors %} {% if error %} <style> #div_id_captcha { margin-bottom: 0px !important; } </style> <span class="invalid-feedback d-block mb-3"> <strong> You must complete … -
Django : Pass a prefetch_related _set.all() in Ajax Search results
I've implemented a table search product with Ajax and it works well. But now, I want to build dynamically my table taking in account the number of my warehouses can be increase. search.js data.forEach((item) => { const newName = (item.nom).slice(0, 30) + "..."; tableBody.innerHTML += ` <tr> <th><a href="{% url 'product-update' ${item.id} %}">${item.sku}</a></th> <td>${item.etat__etat}</td> <td class="small">${newName}</td> <td>${item.famille__nom}</td> <td>${item.mageid}</td> <td>${item.adresse}</td> models.py (model for witch I need a set) class SstStock(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) product = models.ManyToManyField(Produit) qty = models.IntegerField() last_update = models.DateTimeField(default=timezone.now) views.py def search_product2(request): if request.method == 'POST': search_str = json.loads(request.body).get('searchText') products = Produit.objects.filter(sku__icontains=search_str) | Produit.objects.filter( nom__icontains=search_str) | Produit.objects.filter(mageid__icontains=search_str) data = products.values( 'id', 'sku', 'nom', [...] 'sststock', [...] 'cau_cli', 'maxsst2', ) return JsonResponse(list(data), safe=False) Directly in template I could do : template {% for produit in produits %} {{ produit.sku}}<br> {% for sst in produit.sststock_set.all %} <span>{{sst.warehouse.code}} - {{ sst.qty }}</span><br> {% endfor %} <br> {% endfor %} But I couldn't find the way to pass the the sststock_set.all() in the JsonResponse. I got well a "sststock" value in it but it contains only the last value of the set instead of an array/dict of the whole set. console.log() qty: 7 sku: "ACP863" sststock: 68095 68095 is the last … -
How to insert big HTML block in Javascript? Django JS
I have custom.js file in my django website. I need to create django - div in .js catalog.html <div class="row px-3" id="products-section"> #----------------- # This block should be placed from js #----------------- <div class="col-sm-4"> <article class="post post-medium border-0 pb-0 mb-5"> <div class="post-image"> <a href="{% url 'product' product.url %}"> <img src="media/{{product.img}}" class="img-fluid img-thumbnail img-thumbnail-no-borders rounded-0" alt="" /> </a> </div> <div class="post-content"> <h2 class="font-weight-semibold text-5 line-height-6 mt-3 mb-2"><a href="{% url 'product' product.url_dop %}">{{product.name}}</a></h2> <p>{{product.description}}</p> <div class="post-meta"> <span><i class="far fa-user"></i> by <a href="{% url 'brandpage' product.manufacturer_url %}">{{product.manufacturer_name}}</a> </span> <span class="d-block mt-2"><a href="{% url 'product' product.url %}" class="btn btn-xs btn-light text-1 text-uppercase">Подробнее</a></span> </div> </div> </article> </div> #----------------- # End block #----------------- </div> custom.js var parent_div = document.getElementById("products-section"); var product_node = document.createElement("div"); product_node.className = "col-sm-4"; product_node.innerHTML = "Big html block here"; parent_div.append(product_node); How i can add so big block? And also i need to replace django variables by js variables in this block. -
Advise please with what to build workflow for django
I am trying to build a “workflow” for published Articles. I think this system would work by accept an article journal and coauthors. For example, User create article in form, select journal and coauthors and then the article is saved as "draft". Notification about this article send publisher and coauthors. They decide if the data is entered correctly, if not, then send the article back to the author, and if correct, the article is published on the site. I think there are a lot of apps that do this, but not in one I didn’t find how to do it so that the publisher and co-author could take the job without entering the admin. I would like this to be available through a page on the site (views and template). maybe I’m wrong. I’d love to hear any advice from you -
How do I make custom landing page from admin for my application in django?
How Should I redirect if the admin selected a login page or golive or registration? from django.urls import path from demo import views urlpatterns = [ path('registration', views.home, name='registration'), path('login', views.login, name='login'), path('sessionover', views.over, name='over'), path('golive', views.sessionlive, name='live_session'), path('ques', views.qus_send, name='auestionsent') ] -
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.. -
list_filter django with combined fields "A_B"
I want to use the combination of two fields in the django admin (list_filter). Filter by "FieldA_FieldB" A_B A_C Is it possible? How can I do this? Thanks, Davi -
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 …