Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run django view every 24 hours
I want to run django view on server every 24 hours, please help me if you can -
How to delete upto n type of data in self forienkey using django rest framework?
class Directory(models.Model): name = models.CharField(max_length=100) parent_directory= models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True) I want to delete root folder and all the folders which is inside the root folder (root folder means parent_directory is null in Directory model), https://i.stack.imgur.com/oszCR.png, In this picture root is base directory and rest of the all folders are inside the root folder and if i delete the root folder then all the folders which is inside the root folder needs to be deleted ] for exam: root is parent_directory test sub3 and sub4 is inside root directory base on table photo Bhavya is inside sub4 based on photo top is inside in Bhavya Now if I want to delete object number 22 means root directory then 26, 29, 33 and 34 should also be deleted. Would you please let me know how can delete this n type of object without on_delete=models.CASCADE ? -
Hyperlink redirect is not working in Django
I have the below code as part of my project. But instead of redirecting to the HTML page (contact.html), it is redirecting back to the home page or index.html. main_app/urls.py: path("", home_views.index, name='home_page'), path("contact", home_views.contact, name='contact'), main_app/home_views.py: def index(request): return render(request, 'Varsity/index.html') def contact(request): return render(request, 'Varsity/contact.html') Varsity/index.html: <li><a href="{% url 'contact' %}">Contact</a></li> Terminal [05/Sep/2022 14:34:43] "GET /contact HTTP/1.1" 302 0 -
are using django q objects (complex queries) with user input secure? [duplicate]
Is it possible to inject a SQL attack in these queries? is it okay to insert user input in the query directly like below or it need a validation etap in advance : query = self.request.GET.get('q') query_result= Consultant.objects.filter( Q(first_name__icontains=query) | Q(last_name__icontains=query) | Q(group__title_techGroup__contains=query) | Q(practices__title_practice__contains=query) ) -
Is there a way to get custom user model password before it gets hashed on Django
A custom user model was created in Django. After we create a user, we then send that user details to firebase: # Sync User to FireBase Authentication: @receiver(post_save, sender=Account) def add_user_to_firebase(sender, created, instance, *args, **kwargs): if created: auth.create_user(**{ "uid":instance.firebase_uid, "display_name": instance.username, "email": instance.email, "password": instance.password }) but this is where the issue comes in: when we send the password instance.password the password is then hashed before it gets sent to firebase. We want the unhashed password to get sent to firebase instead. Is that possible? -
AttributeError: type object 'ConsignacionDetalle' has no attribute 'objects'
Aqui se guardan diferentes precios para los diferentes productos class ProductoPrecioVenta(models.Model): precio = models.FloatField(default=0) val_seleccion = models.BooleanField(default=True, verbose_name="Act.") val_activo = models.BooleanField(default=True, verbose_name="Act.") producto = models.ForeignKey( Producto, on_delete=models.PROTECT, verbose_name="Productos") producto_precio_descripcion = models.ForeignKey( ProductoPrecioDescripcion, on_delete=models.PROTECT, verbose_name="Precio Descripción") moneda = models.ForeignKey( Moneda, on_delete=models.PROTECT, verbose_name="Monedas") created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: verbose_name = "producto precio de venta" verbose_name_plural = "productos precios de ventas" def __str__(self): return "{} | {} | LMT. {} | {} {}".format(self.producto.nombre, self.producto_precio_descripcion.descripcion, self.producto.limite, self.moneda.simbolo, self.precio) ProductoPrecioVenta.form class ProductoPrecioVentaForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProductoPrecioVentaForm, self).__init__(*args, **kwargs) self.fields['producto'].queryset = Producto.objects.filter( val_activo=True) self.fields['producto_precio_descripcion'].queryset = ProductoPrecioDescripcion.objects.filter( val_activo=True) self.fields['moneda'].queryset = Moneda.objects.filter(val_activo=True) class Meta: model = ProductoPrecioVenta fields = ['producto', 'producto_precio_descripcion', 'moneda', 'precio'] labels = { 'producto': 'Producto', 'producto_precio_descripcion': 'Descripción para el Precio', 'moneda': 'Moneda', 'precio': 'Precio de Venta', } widgets = { 'producto': forms.Select( attrs={ 'class': 'form-select h-50 w-100', } ), 'producto_precio_descripcion': forms.Select( attrs={ 'class': 'form-control h-50 w-100', } ), 'moneda': forms.Select( attrs={ 'class': 'form-control', 'style': 'text-align:right;', } ), 'precio': forms.NumberInput( attrs={ 'class': 'form-control', 'style': 'text-align:right;', } ), } Se hace declara producto_precio_venta, que hace referencia a ProductoPrecioVenta class ConsignacionDetalle(models.Model): cantidad = models.IntegerField(verbose_name="Cantidad") val_activo = models.BooleanField(default=True, verbose_name="Act.") consignacion = models.ForeignKey(Consignacion, on_delete=models.PROTECT, verbose_name="Consignación") producto_precio_venta = models.ForeignKey(ProductoPrecioVenta, on_delete=models.PROTECT, verbose_name="Precio de venta") created_at = … -
Django employee working hours plan app based on date
I need to make an app that runs based on date. The idea is, have a total count on work hours that a divided by some number to get the right number of open positions to be filled with employees. When employees filling positions they should have their status and working hours bound to a from date, to date field, multiple from date, status, working hours, to date fields are necessary. And now visitors should have the option to input some date to view the future of open positions and needed working hours while also shown the employees with the status and working hours within that date range. I want to use django for that but have no clue how to accomplish such task. My idea was bound this whole thing into a calendar and let visitors just click on some date to show them the data but also dont know how to implement that. Do you have any ideas or direction you could guide me to ? -
Django - Bootstrap table inline editing
I have a data table with all functionalities like sort and search. I want to add a col in the table that could be editable. I want to save the comments of the viewer. I have the column in my model.py. but I do not know how to save it and keep it editable. <tbody> <tr> {% for a in data %} <td><a id="idclicked" href="datadescription/{{a.id}}/" title="click to see Metadata" style="color: rgb(30, 61, 199); font-weight:bold;"><u>{{ a.id }}</u></td></a> <td>{{ a.Date }}</td> <td>{{ a.Name }}</td> <td>{{ a.Affliations}} </td> <td>{{ a.Methods}}</td> <td>{{ a.Instruments}}</td> <td>{{ a.device}}</td> <td>{{ a.comments }}</td> <td contenteditable="true">{{ a.editablecomments }}</td> -
How to fetch rows from a table based on a field which is present in a different table having a foreign key relationship with it?
Context I have two tables as follows in Django Table1: - id - name - address - state - short_code Table2: - id - table1_id - property (searchable field) Relationship between Table1 and Table2: Table1(1) -> Table2(n) [ 1->n ] Question Let's say I have a searchable property p1 in Table2. How to fetch all the rows from Table1 which is satisfying the following query parameters? short_code, state, and property as p1 from Table2 Remember, Table1 1:n relationship with Table2, so Table2 can have multiple rows satisfying foreign key relationship of field id from Table1. Any help will be greatly appreciated. Have been working on the problem for a long time now. Thanks in advance. -
Multi-Language website using Django JS, facing error on Search filter error
I'm building a multi-language Django site and using 'Django-parler' for my model data translations. Now I'm wondering if there is a Django search app that works with multi-language models and I used to create the search functionality here, it works fine for single-language sites. But, I can't get it to work with multiple language filter functions. Here is my models.py from django.db import models from parler.models import TranslatableModel, TranslatedFields class Category (TranslatableModel): translations = TranslatedFields( category_Title=models.CharField(max_length=500) ) def __str__(self): return self.category_Title class Faq_QA(TranslatableModel): translations = TranslatedFields( question_Title=models.CharField(max_length=500), question_Description=models.TextField(), category_Option=models.ForeignKey(Category, on_delete=models.CASCADE), SEO_Keywords=models.TextField(), ) def __str__(self): return self.question_Title Here is my search View.py from django.shortcuts import render from .models import Category, Faq_QA from django.db.models import Q # Create your views here. def base(request): if 'q' in request.GET: q = request.GET['q'] multiple_keywords_faq = Q(Q(question_Title__icontains=q) | Q(question_Description__icontains=q)) search_key_faq = Faq_QA.objects.filter(multiple_keywords_faq) else: search_key_faq = Faq_QA.objects.all() context = { 'search_data': search_key_faq, 'category_data': Category.objects.all(), } return render(request, 'Base.html', context) For references my error-throwing image is here; Multi-Language website Error on Search filter image is here - please refer to it Can anyone please help me with this error, -
Django Tag Info
There are some wrong book links for the Django tag info. Since I do not have editing priviliges (It keeps saying edit queue is full.), I figured this would be the next best way. The books that need correction are: Pro Django Test Driven Development with Python -
VueJS + django_microsoft_auth + django REST framework authentication
I am having troubles logging in with Microsoft Authentication with my current stack. The Django application successfully logs in via MS auth using django_microsoft_auth (a legacy website section uses Django templates), but I can't figure out how to integrate it with the newer SPA section (as of now I managed to create a separate login with Django REST framework). Could you please give me any hint? Thank you! -
Dynamic Sitemap Django for not use model and only use api
Please help me. I am developing odoo ecommerce project. I use frontend with Django framework and backend with python. I give api from backend to Django frontend. Please let me know how to write dynamic sitemap. I am not have model to import and only use api. -
How can I use date as x axis Plotly Dash
I just started using Plotly Dash. I have this existing app that can generate random data. How can I change the X Axis to today's date. I tried using "datetime.datetime.now()" but the date looks like this image import dash from dash.dependencies import Output, Input import dash_core_components as dcc import dash_html_components as html import plotly import random import plotly.graph_objs as go from collections import deque import datetime from django_plotly_dash import DjangoDash X = deque(maxlen=10) X.append(1) Y = deque(maxlen=10) Y.append(1) x_new = datetime.datetime.now() app = DjangoDash("SimpleExample") app.layout = html.Div( [ dcc.Graph(id='live-graph', animate=True), dcc.Interval( id='graph-update', interval=1*2000 ), ] ) @app.callback(Output('live-graph', 'figure'), [Input('graph-update', 'n_intervals')]) def update_graph_scatter(input_data): X.append(X[-1]+1) Y.append(Y[-1]+Y[-1]*random.uniform(-0.1, 0.1)) data = plotly.graph_objs.Scatter( x=[x_new], y=list(Y), name='Scatter', mode='lines+markers' ) return {'data': [data], 'layout': go.Layout(xaxis=dict(range=[min(X), max(X)]), yaxis=dict(range=[min(Y), max(Y)]),)} if "SimpleExample" == '__main__': app.run_server(host='0.0.0.0', port=8080, debug=True) -
From within a Django Rest API, how can I return an image from an external image API that requires a key in the address
I am writing an API with the Django Rest Framework that returns a random image from an external image API that I have access to, which requires a private key in the url: imgapi.com/193811&key=2s3kp72a82 Without exposing the key, I want an endpoint in my API to return the image from this url: mysite.com/randomimage I will ise this endpoint as part of a web app that has a button that when clicked, displays a random image loaded via JS with an AJAX call to the endpoint. One of the approaches I tried was: @api_view(['GET']) def random_image(request): response = requests.get('api url with secret key') if request.method == 'GET': return HttpResponse(response.content, content_type="image/jpeg") however when I go to this endpoint in my browser, I get a server 500 error. When I make this a POST endpoint instead, I can get the image to return in Postman, but not in the browser. I have also tried to display the GET request using a Django template, but I cant get that to work either. -
why static files are not included?
Static files don't work. I seem to have registered everywhere where necessary. But the problem remains. What could be the catch. settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') urls from django.urls import * from . import * from django.conf.urls.static import * from django.contrib.auth import views as auth_views from django.conf import settings from blog import views app_name = "blog" urlpatterns = [ path('', views.index), path('create', views.create, name='create') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) dir structure -
Django REST API 504 Gateway Time-out Error
so I have this API that takes a post request and needs almost 3 minutes to process and return some results in response. I've tried all the ways mentioned in this link -
Django How to generate and save image when entity made with CreateView?
I'm currently developing a django aplication. With one of my models I need to generate a barcode and save it as an image and upload it in one of the models field. I tried to generate the image in the save function of the model as shown bellow. The image is generated and saved to the correct folder, but when I look at the entitys they always have the default image saved with them. models.py: class ItemEntity(models.Model): sub_type = models.ForeignKey(ItemSubType, on_delete= models.PROTECT) location = models.ForeignKey(WarehouseBin, on_delete= models.PROTECT) supplyer = models.ForeignKey(ItemSupplyers, on_delete= models.PROTECT) quantity = models.IntegerField() unit = models.ForeignKey(Units, on_delete= models.PROTECT) creation_date = models.DateTimeField(default= timezone.now) expiration_date = models.DateTimeField() time_of_consumption = models.DateTimeField(null= True) barcode = models.ImageField(default='default_barcode.jpg', upload_to= 'media/barcodes') def __str__(self): return self.sub_type.name + " " + str(self.quantity) + " " + str(self.unit) def save(self): super().save() datas=self.pk,self.location,self.sub_type # Datas to give to my barcode generator code self.img = Image.new('RGB',(1,1)) # Declaring an empty image variable BarcodeGenerator(datas,self) # Barcode generator the barcode it generates is put intu self.img variable self.img.save("/home/makiverem/projects/pina/media/media/barcodes/"+str(self.pk)+".jpg") # Saving the image to media/media/barcodes #I MISS SOMETHING FROM HERE I THINK self.barcode=self.img #Making the models barcode field equal to self.img views.py: class ItemEntityCreateView(CreateView): model=ItemEntity form_class = ItemEntityForm def get_form_kwargs(self, *args, **kwargs): kwargs … -
how to save Ratelimit result in Redis in Django
I'm using in ratelimit to limit the requests to my server in Django, I can see that ratelimit uses Django cache to count the request etc.. and I want to change it to be in Redis. my motivation is to change it only for the ratelimit and not for all of my application caching. there is any configuration for that? Thanks! -
Django Navbar No Reverse Match error - how do I fix this?
I'm receiving the below error when trying to link up my navbar in base.html in Django. NoReverseMatch at / 'home' is not a registered namespace I'm not sure why it's not working, any help would be much appreciated! base.html: <ul class="nav navbar-nav ms-auto"> <li class="nav-item"><a class="nav-link text-white" href="{% url 'home:home' %}"><strong>Home</strong></a></li> <li class="nav-item"><a class="nav-link text-white" href="{% url 'home' %}"><strong>My Health</strong></a></li> <li class="nav-item"><a class="nav-link text-white" href="{% url 'login' %}"><strong>Login</strong></a></li> <li class="nav-item"><a class="nav-link text-white" href="{% url 'signup' %}"><strong>Signup</strong></a></li> </ul> urls.py: urlpatterns = [ path('', views.home, name='home'), path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))), path('success/', views.success_view, name='success'), ] views.py: def home(request): return render(request, 'HealthHub/home.html') -
Django - Twilio schedule message is not sending
I am trying to send SMS via schedule message send functionality using Twilio. However, messages are not sent as per the scheduled time. Here is my code. message = clientSMS.messages.create( media_url=attachimage, body=editor, from_=settings.SERVICE_ID, to=selectedphone, schedule_type='fixed', send_at=FinalScheduleTime.isoformat() + 'Z', ) Message SID is generated successfully. But the SMS is sent at the scheduled time. Is there anything that I am missing out on, Please help me. -
how to collect all anchor_text_link and anchor_text with conataing single title and published_post in one object
[{'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link': 'https://duhjodnon.fdgh', 'anchor_text': 'dhjijnjfoen'}, {'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link': 'https://duhjodnon.in', 'anchor_text': 'nnnlnlkmn'}, {'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link': 'https://dhdjjdnjn.connnn', 'anchor_text': 'mdnkbuhvsinksmjbxua'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://googlabhgahbhe.cm', 'anchor_text': 'nbsuhguhbd'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://gahihabb.insj', 'anchor_text': 'frfbrfbrbf'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://googlabhgahbhe.cmajakn', 'anchor_text': 'fbwefibwe'}, {'pubished_post': 3, 'anchor_title': 'this game title', 'anchor_text_link': 'https://trwtfuhwbhbsguv.jcbc', 'anchor_text': 'wenfbiwebfjibewif'}, {'pubished_post': 2, 'anchor_title': 'jsbhbsjh valorent pc game', 'anchor_text_link': 'https://gdmskmksm', 'anchor_text': 'jhdjihdjnjdn'}, {'pubished_post': 2, 'anchor_title': 'jsbhbsjh valorent pc game', 'anchor_text_link': 'https://hrfsbsm.cm', 'anchor_text': 'vbhbdibejid'}] I want this object be like {'pubished_post': 4, 'anchor_title': 'another broken link article test', 'anchor_text_link':['https://duhjodnon.fdgh','https://duhjodnon.in','https://dhdjjdnjn.connnn'], 'anchor_text': ['dhjijnjfoen','nnnlnlkmn','mdnkbuhvsinksmjbxua']}, Similarly for same thing for other objects too PLZ someone help i wanted to covert all the objects in single object with one title and published_post with all the links and text -
django migrations not working in docker container
I have a project developed in djnago and when i add a new field to models.py and run makemigrations and migrations it works fine , my problem is when i run docker container it seems the migartions are not applied and new field is not added to model since i get this error when i try to open the admin panel : ProgrammingError at /admin/ column account_profile_user.uid does not exist LINE 1: ...er"."level", "account_profile_user"."user_photo", "account_p... which uid is new field that i added to models.py . this is Dockerfile: FROM python:alpine RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && apk add jpeg-dev zlib-dev libjpeg libffi-dev ENV CRYPTOGRAPHY_DONT_BUILD_RUST=1 WORKDIR /app COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt COPY . /app/ ENTRYPOINT [ "./entrypoint.sh" ] and this the entrypoint.sh : #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi python manage.py makemigrations python manage.py migrate python manage.py collectstatic --noinput exec "$@" and this is docker compose: services: account: build: context: . dockerfile: Dockerfile env_file: - ./envs/development.env volumes: - ./:/app - /store/account/media:/app/media - /store/account/static:/app/static … -
Why does it give an error "not a registered namespace"?
I'm trying to make a data entry form without using forms.py. When trying to display the form, it gives the error "'blog' is not a registered namespace". I think that I could confuse something with urls.py. urls.py from django.urls import * from . import * from django.conf.urls.static import * from django.contrib.auth import views as auth_views from django.conf import settings from blog import views blog = "blog" urlpatterns = [ path('', views.index), path('create', views.create, name='create') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) vievs.py def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.save() return render(request, 'create.html') -
Decrypt function not working in python, below is the code
import hashlib from binascii import hexlify from binascii import unhexlify from Crypto.Cipher import AES class AppCrypto: __KEY: str = None __iv = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" def __init__(self, key: str = None) -> None: """ Initialize the class. :param key: The key for the Encryption and Decryption. """ self.__KEY = key def pad(self, data: str): """ Pad the data to be encrypted. :param data: The str data to be encrypted. """ length = 16 - (len(data) % 16) data += chr(length) * length return data def unpad(data): return data[0:-ord(data[-1])] def __get_cipher(self) -> AES: """ Get the cipher object. :param key: The key to be used for encryption. """ bytearrayKey = bytearray() bytearrayKey.extend(map(ord, self.__KEY)) return AES.new( hashlib.md5(bytearrayKey).digest(), AES.MODE_CBC, self.__iv.encode("utf-8"), ) def encrypt(self, plainText: str) -> bytearray: """ :param data: The data to be encrypted. :return: The encrypted data. """ plainText = self.pad(plainText) enc_cipher = self.__get_cipher() return hexlify(enc_cipher.encrypt(plainText.encode("utf-8"))).decode("utf-8") def decrypt(self, encryptedText: str) -> str: """ :param data: The data to be decrypted. :return: The decrypted data. """ dec_cipher = self.__get_cipher() data = unhexlify(dec_cipher.decrypt(encryptedText).decode('utf-8')).encode("utf-8") return self.unpad(data) from AppCrypto import AppCrypto appCrypto = AppCrypto("729C6F92987DCEF8D955D23ED2269354") enc_data = appCrypto.encrypt("Hello, Ninranjan") Output: 0f657d48535896ab573a4cb7e9a967e8d409b7f4f537c3157949abd91e221bf2 plain_tx = appCrypto.decrypt("0f657d48535896ab573a4cb7e9a967e8d409b7f4f537c3157949abd91e221bf2") gives error like TypeError at /propertytax/receipt_entry/ Object type <class 'str'> cannot be passed to …