Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
how set model for comments-django-xtd
hi guys im new in django. i need to have comments,replay comments, like and dislike, count of replays, numbers of likes and dislikes. so i found django-comments-xtd package. i tried to set it in my project but i didnt found any documenttions that explains well about how use it. i found this link about that but it doesnt explain how i should define my model -
How do I fix my django admin page not loading css although having correct configuration?
I am aware this question has been asked a thousand times, but none of the solutions have worked for me... I was working on the Django tutorial, but when I created the superuser, and entered the admin page, the css was missing. The weird thing is, is that when I check the page source from chrome, and click one of the css references in the html, my computer manages to download the stylesheet. It only had a relative path, and when using chrome's debugger, I can see the page taking some time to download the css. So I guess the static paths are configured correctly, the page actually loads the css, but somehow it is not reflected in the view? I have no idea how such a thing can happen. Things I have tried until now: Setting STATIC_URL Setting STATIC_ROOT Setting PROJECT_DIR Setting static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) to urlpatterns Deleting static files and doing manage.py collectstatic every time i modified any files Making migrations again Adding base dir + "templates" to TEMPLATES Setting DEBUG from False to True again I must be missing something simple, but I can't see it. Any help is greatly appreciated. In settings.py: PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = … -
Django Grouping(annotating) by Order and Get all Values
I have following model class Attempt(BaseModel): category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) answer = models.ForeignKey(to=ModelAnswer,null=True, blank=True,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) order = models.PositiveIntegerField(null=True, blank=True) def __str__(self): return self.category.name class Meta: ordering = ['order'] This model will have 10 records for common order id i.e 1 if there are 10 records on the attempt model same order number will be assigned to them i.e order =1 for the next 10 attempt, same order will be assigned i.e order=2 because 10 records are added at once. I just want to show those 10 records inside the same array as the response having order = 1 and next array for order=2 here are my views class ListAttemptSerializer(generics.ListAPIView): serializer_class = serializers.AttemptSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): data = Attempt.objects.filter(user=self.request.user).values('order').annotate( total=Count('order') ).all() return data Serializer.py class AttemptSerializer(serializers.Serializer): answer = ListAnswerSeiralizer(many=True) category = serializers.CharField() class Meta: model = Attempt fields = [ 'category', 'answer', ] My expected response will somehow look like this [ {"answer": [{ "id": 1, "user": 1, "questions": "what are the facts of this situation?", "subcategory": "Circumstance", "is_intentional": "True", "answer": "string", "created_at": "2022-09-05T10:59:59.551583" }, { "id": 2, "user": 1, "questions": "what are the facts of this situation?", "subcategory": "Circumstance", "is_intentional": "True", … -
how add row dynamically in django formset
In my django app I have two models i.e Product and Real which are connected by many to many relationship. To add the data dynamically in my tables I want to use javascript to Add row or Remove Row button in my forms but unable to do so. Here are the details: Models.py from dataclasses import Field from django.db import models class Product(models.Model): name = models.CharField(max_length = 150) quantity = models.IntegerField() cost = models.DecimalField(max_digits=15, decimal_places=0) sell = models.DecimalField(max_digits=15, decimal_places=0) class Real(models.Model): payment_id = models.CharField(max_length = 150) company = models.CharField(max_length = 150) product = models.ManyToManyField(Product, symmetrical=False) Forms.py from .models import Product, Real from django import forms from django.forms import formset_factory class ProductForm(forms.Form): name = forms.CharField() cost = forms.DecimalField() sell = forms.DecimalField() quantity = forms.IntegerField() ProductFormset = formset_factory(ProductForm) class RealForm(forms.Form): payment_id = forms.CharField() company = forms.CharField() product = ProductFormset() Views.py from django.shortcuts import render, redirect from django.forms import modelformset_factory from .models import Product, Real from .forms import RealForm, ProductForm, ProductFormset def post(request): if request.POST: form = Real(request.POST) form.product_instances = ProductFormset(request.POST) if form.is_valid(): real = Real() real.payment_id = form.cleaned_data['payment_id'] real.save() if form.product_instances.cleaned_data is not None: for item in form.product_instances.cleaned_data: product = Product() product.name = item['name'] product.cost = item['cost'] product.sell = item['sell'] product.sell = … -
Plot Chart.js scatter graph in Django using huge data
I'm developing a scatter graph to visualize the trend of product volume for every product count. x: product count y: product volume From django view, two array list was pass to chart javascript in django template. Here is the code: <script> const volume = {{product_volume}} // <--- array list of product_volume const count = {{product_count}} // <--- array list of product_count const p1ctx = document.getElementById('VolumeChart'); const P1Chart = new Chart(p1ctx, { data: { datasets: [{ type: 'scatter', label: 'Volume', data: volume, // <-------------------- Target to assign 'x' and 'y' data backgroundColor: 'rgb(255, 99, 132)' }], }, . . . </script> However, with huge data (approx.: 15,000), how can I simplify the process of data labelling in the JavaScript using array list of product count and product volume? -
how to autoupdate category by the amount of products in django model
I have a model of the category with title and count and I also have another model called Products which has category as one of its foreign-key. How can I auto-update the category count field by the number of products that comes under the same category? class Category(models.Model): title = models.CharField(max_length = 20) count = models.IntegerFIeld() class Product(models.Model): title = models.CharField(max_length = 20) category = models.ForeignKey(Category, on_delete = models.CASCADE) -
Only one json displays on localhost [closed]
I simply put JSON in variable li and try to show in localhost by return JsonResponse(li) But from the original list [{'_id': 'SC', 'cast_count': 60576}, {'_id': 'General', 'cast_count': 562298}, {'_id': 'OBC', 'cast_count': 389510}, {'_id': 'ST', 'cast_count': 2700}, {'_id': '', 'cast_count': 1904}] I got only random one of this such as: {'_id': 'ST', 'cast_count': 2700} Instead of the full list that has to display Note: I know I'm lacking in basic concept of django so pls help me and if there is some problem in question pls comment or flag instead of downvote