Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get orders of 1 user in a same cell in a row
I'm trying export data to a csv file using Django or JavaScript and I want the output like this. NAME Orders Robert Hammer Nails Gloves -------- -------- George Screws but the output in csv shows the other Orders of Robert are in the same line column of NAME instead of Orders -
Python format a string date to actual format gives me error
Code: date_format_str = "%Y-%d-%m %H:%M:%S%z" starttime = datetime.strptime(startdate, date_format_str) Error: ValueError: time data '2022-12-20 10:18:00+00:00' does not match format '%Y-%d-%m %H:%M:%S%z' -
Django queryset return bool when the object was created on the last month
So I'm trying to make this query: queryset = ( Offer.objects.annotate( is_new=Case( When( created_at__month=[ now.month ], then=Value("True"), ), default=Value("False"), ) ) .values("is_new") ) Basically what i want is to return a new booleand field that tells me "true" if the offer was created on the last month. But I'm getting the following error: TypeError: Field 'None' expected a number but got [1]. Does anyone know why this happens? or how can I fix it? Also I thank you If you have a better approach. Thanks in advance :) -
How to authenticate user form credentials from PostGresql with Django
I am able to register users to my custom table in the postgresql database. I would like to know how can I use the credentials from my postgresql table to authenticate login from my django web app. I know I have to create a custom backend but I don't know how we can import the credentials from postgresql to authenticate against the credentials that user entered. My model: from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser # Create your models here. # Database model Users has one to one relationship with Django User table from django.db.models.signals import post_save from django.dispatch import receiver class Profile(AbstractBaseUser): first_name = models.TextField() last_name = models.TextField() user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) user_name = models.TextField(unique=True) email = models.TextField() password1 = models.TextField() password2 = models.TextField() date_created = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'user_name' REQUIRED_FIELDS = [] def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() I have my django project pointing towards my custom user model too. I just don't know how to create a custom backend for authentication. If I could be guided towards it, I would really appreciate. -
MS Access slow with remote database - switch to web app?
I have many ms access apps with databases hosted on-site at the clients facilities... however, some clients have move to virtual remote servers to host the databases (SQL Server) and it has caused a performance issue on the front end. I have looked through my code, made sure queries are pulling minimal data, etc. but it is still a laggy experience. My only thoughts are to force the client to move data back on site (not great since some share data between multiple remote sites, so only one site would see an improvement), or maybe get them to upgrade to a better server situation (faster? more ram? not sure...). In any case - it might be time to move to something beyond Access. Access can do great things, but it is hard for me to give people access offsite (at least quick access), and clients are always wanting to use 'ipads'... and rather than buying windows tablets, and worry about versions of office, etc. it may be time to move to a web interface. I could add a webserver internally and make it available to the outside via VPN only... it would be secure that way (well, as secure as … -
Why did I get Template does not exist error, though it appears Django offers flexibility with respect to folder structure?
I have read several posts here where people discussed their preferred directory structure to keep various files of their Django project. But I get a file-does-not-exist error if I put my templates in the inner my_project folder instead of the outer my_project folder which contains the manage.py file. Is there some config file that specifies the default location of the templates (and other files)?can you please help me with the command change if I put templates in the inner (sub) folder? I just began my first Django project and would appreciate your help. -
Django (Both in backend and frontend) or Django Rest Framework + React? [closed]
I would like to develop a website (like Zillow) by myself and I don't know if it would be easier to do it using only Django (with Django templates and vanilla Javascript) or Django Rest Framework and React. I have experience in React but I do not enjoy writing a separate backend and frontend. Also I don't like React that much. Is it possible, easier and better for only one dev to use only Django for a project like that? -
What is "list_display_links" for Django Admin? [duplicate]
I have Person model below: # "store/models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField() def __str__(self): return self.first_name + " " + self.last_name Then, I assigned "first_name", "last_name" and "age" to list_display in Person admin as shown below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ("first_name", "last_name", "age") # Here Now, FIRST NAME, LAST NAME and AGE are displayed as shown below: Next, I assigned "first_name", "last_name" and "age" to list_display_links in Person admin as shown below: # "store/admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ("first_name", "last_name", "age") list_display_links = ("first_name", "last_name", "age") # Here But, nothing happened to the "change list" page as shown below: So, what is list_display_links? -
Create 'Export As CSV' Button in Django on HTML Webpage [duplicate]
I currently have a working django application that has a view that outputs a dataframe and is rendered onto a .html page. Now, I am trying to create a button on this .html page that allows the user to download the rendered table to their local downloads folder. How is this done? I am yet to figure it out after doing lots of research trying to get a table from views to html to downloaded as csv. Thank you! Python code in views.py results_html = results.to_html(index=False) return render(request, 'output.html', {'results_html': results_html}) my current home.html code <html lang="en-US"> <body> <table>{{results_html|safe}}</table> </body> </html> I have looked into this and would like more clarification about where to type each thing.I am brand new to Django and still trying to figure out how each file interacts. -
how to use twilio webhook to reply to an sms in production
I am new to Twilio services and just started using their api for sms with django. the sms outbound work well and now i want to make sure to grab the value replied by the person who has received the message. Locally, I have used Ngrok as a webhook, I provided the Ngrok URL generated while running my python application locally + backend api endpoint URL in the Twilio SMS settings required for the webhook and it work. Please note that i made sure that the URL the SMS response is supposed to hit is publicly available. Now my question is how do I make this work on a production environment where i cannot run Ngrok from my computer? I removed the Ngrok URL provided since its not running locally and left the URL of the endpoint but i am not receiving anything back as a response. -
Doing something when payment is successfull with stripe and DjangoRest
I integrated stripe payment in my projects so now i can make a payment. My app about an advertising app so the ad keep active for 30 days then disappear so i want to use payment to extend the expiration date of the ad. Here is Payment view: class StripeCheckoutView(APIView): def post(self, request): try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': 'price_1MPUIXGslCuRnIIuUV1ME6Kn', 'quantity': 1, }, ], payment_method_types=['card',], mode='payment', success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}', cancel_url=settings.SITE_URL + '/?canceled=true', ) return redirect(checkout_session.url) except: return Response( {'error': 'Something went wrong when creating stripe checkout session'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) models: class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise") category = models.CharField(max_length= 200, choices = CATEGORY) location = models.CharField(max_length= 200, choices = LOCATIONS) description = models.TextField(max_length=600) price = models.FloatField(max_length=100) expiration_date = models.DateField(default = Expire_date, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) EDIT : I want to use payment to extend the duration of the expiration date. So when the user made the payment the expiration date be 60 days. -
Django ORM filtering using dates and data on separate one to many rows with the same related_name
These three models track manufacturing processes through a mix of user defined statuses, and three predefined statuses, which are 'Initialized', 'Scrapped', and 'Complete'. Every processes first status is always "Initialized" and their final status is always either "Scrapped", or "Complete". All statuses in between are user defined and don't matter for this query. models.py #simplified for clarity class Process(models.Model): name = models.CharField(max_length=50) class Status(models.Model): name = models.CharField(max_length=50) class ProcessStatusHistory(models.Model): timestamp = models.DateTimeField() prev_status = models.ForeignKey(Status,related_name="prev_status", on_delete=models.CASCADE) new_status = models.ForeignKey(Status,related_name="new_status", on_delete=models.CASCADE) process = models.ForeignKey(PatientVisit,related_name="of_process", on_delete=models.CASCADE) The user can create a report with a date range picker. What is the cleanest way to ask the DB for the following: All ProcessStatusHistory rows (even outside of the date range) for processes that were: not 'Initialized' after the later date in the date range picker (case: Process not yet started for date range) AND were not yet 'Scrapped' OR 'Complete' before the earlier date in the date range picker (case: Process already finished for date range). In essence, I am aiming to get all ProcessStatusHistory information for all Processes that were 'Open' at any point in the date range picker. My attempt so far, which works inefficiently, but does work is: Make a list … -
Saving ListFields and CustomFields to Database - Django
I am very new to Django and I am trying to understand how I can save fields to the db. I have the following model class CashFlow(models.Model): Id = models.AutoField(primary_key=True) CompanyId = models.ForeignKey(Company, on_delete=models.CASCADE) PeriodInstant = models.TextField() PeriodStartDate = models.TextField() PeriodStartDateEndDate = models.TextField() Currency = models.TextField() Decimals = models.TextField() CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = models.TextField( null=True) NetIncomeLoss = models.TextField(null=True) Serializer: class PeriodSerializer(serializers.Serializer): instant = serializers.CharField() startDate = serializers.CharField() endDate = serializers.CharField() class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer(serializers.Serializer): decimal = serializers.CharField() unit = serializers.CharField() period = PeriodSerializer(many=True) value = serializers.CharField() class NetIncomeLossSerializer(serializers.Serializer): decimal = serializers.CharField() unit = serializers.CharField() period = PeriodSerializer(many=True) value = serializers.CharField() class CashFlow(serializers.Serializer): CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer( many=True) NetIncomeLoss = NetIncomeLossSerializer() class CashFlowSerializer(serializers.Serializer): serializers.DictField( child=CashFlow()) I also created a model serializer so that I can map the fields to this model and store them in the database class CashFlowModelSerializer(serializers.ModelSerializer): class Meta: model = CashFlow fields = ('CompanyId', 'PeriodInstant', 'PeriodStartDate', 'PeriodStartDateEndDate', 'Currency', 'Decimals', 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents', 'NetIncomeLoss') View if request.method == 'GET': jsonData = '' data = getData('TestCompany') allFilings = itemgetter('filings')(data) for item in allFilings: linkToFilingDetails = itemgetter('linkToFilingDetails')(item) jsonData = get_data(linkToFilingDetails, "StatementsOfCashFlows") check = CashFlowSerializer(data=jsonData) if (check.is_valid()): print("ready to send to db") return JsonResponse(jsonData, safe=False) JSON data = http://jsonblob.com/1063218156159647744 Also, since CompanyId is not a field included in the … -
Django Forms and query limit of ModelChoiceField queryset
Creating a form inheriting the "forms.ModelForm" class number = forms.ModelChoiceField(queryset=Number.objects.order_by('?')[:6], empty_label=None) the result is a Choice form is created and random numbers limited to 6 entries will appear. but data indicating the limit is not accepted. if you make the code like this without a limit number = forms.ModelChoiceField(queryset=Number.objects.order_by('?'), empty_label=None) then all records appear in the form and the form is validated everything is fine. P.S SELECT "number"."number" FROM "number" ORDER BY RAND() ASC LIMIT 6 when requesting a limit, the log shows that it works perfectly with LIMIT I am need help pls) -
Why is the delete button not added to my page?
Where is the error in my code? {% extends "base.html" %} {% block content %} <a href="" type="button" class="btn btn-danger">Delete</a> <h3>{{todo.title}}</h3> <smal>{{todo.create}}</smal> <p>{{todo.body}}</p> {% endblock %} I also changed the a tag to button but it still didn't work Thank you for your guidance -
How use FileField model with ReportBro with Django?
I have a FileField field in a Django model that I want to read to display in my ReportBro report that use AWS S3 Bucket. class Inspection_File(models.Model): inspection = models.ForeignKey(Inspection, null=True, on_delete=models.CASCADE, related_name='fk_inspection_inspectionfile') imageNumber = models.IntegerField(null=True, blank=True) file_name = models.CharField(max_length=500, null=True, blank=True) file = models.FileField(max_length=500, storage=InspectionDataStorage(), null=True, blank=True) thumbnail = models.CharField(max_length=500, null=True, blank=True) category = models.ForeignKey(Inspection_File_Category, null=True, on_delete=models.CASCADE, related_name='fk_inspfilecategory_inspectionfile') commentary = models.TextField(blank=True, null=True) class Meta: db_table = 'ins\".\"file' ReportBro has 3 ways to print images, open a local file, by base64, or by URL images_reportbro. However, in my case, using the URL is a very long process, so I need to read the file to keep it in memory and send it directly to the report. Try using this code: test = image.file.open(mode='rb') It has not worked, the report does not give me an error but the spaces appear blank, as if it did not recognize the type of file that I am sending. But when I open a file from my directory it works. When reviewing the data types I realized that locally I have an io.BufferedReader and in the other a FileField Class. marker_image = open('media/db model.png', 'rb') # <class '_io.BufferedReader'> test = image.file.open(mode='rb') # <class 'django.db.models.fields.files.FieldFile'> In … -
Django Docker Postgresql database import export
I have a problem with postgresql database. I just want to able to export and import database like .sql file. But when using command line I am able to get .sql database file but when I'm trying to import it to database it's giving syntax errors in sql file. I can try to fix syntax errors in sql file but I don't want to solve this problem it like that. I need to get exported sql file without any errors and to be able to import it without any issue. What can be a problem? Postgresql version:postgres:14.6 -
if response.get("X-Frame-Options") is not None: Exception Type: AttributeError at /index/ Exception Value: 'tuple' object has no attribute 'get'
from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.shortcuts import render,redirect from .models import User,Post from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect,JsonResponse from django.core.paginator import Paginator import json # Create your views here. def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request,"blog/register.html",{ "message":"Password must match" }) try: user = User.objects.create_user(username,email,password) user.save() except IntegrityError: return render(request,"blog/register.html",{ "message": "Username already taken." }) return render(request,"blog/register.html") def login_view(request): if request.method == "POST": username = request.POST["username"] psw = request.POST["password"] user = authenticate(request,username=username,password=psw) if user is not None: login(request,user) return HttpResponseRedirect(reverse("index")) else: return render( request,"blog/login.html",{ "message":"Invalid username and/or password." }) return render(request, "blog/login.html") def logout_view(request): logout(request) return HttpResponseRedirect(reverse("index")) def addPost(request): if request.method == "POST": body = request.POST["body"] post = Post(user= request.user, post = body) post.save() return render(request,"blog/addpost.html") def index(request): posts = Post.objects.all() # paginator = Paginator(posts, 10) # page_number = request.GET.get('page') # page_obj = paginator.get_page(page_number) return render(request,"blog/index.html", {'page_obj': posts}), # def edit_post(request,post_id): # posts = Post.objects.get(id=post_id) # if request.method == 'POST': # textarea = request.POST["body"] # posts.post = textarea # posts.save()from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.shortcuts import render,redirect from .models … -
how to get id of current object
how to get current id instead of static id (7) to add image to flat ''' class CreateFlat(CreateAPIView): serializer_class = CreateFlat queryset = Flat.objects.all() permission_classes = [AllowAny] def post(self, request, *args, **kwargs): print(request.data) my_img = request.data['id_image'] ima = Images.objects.get(id=my_img) print(self.id) print(self) flat = Flat.objects.get(id=7) flat.images.add(ima); serializer = FlatSerializer(flat, many=True) return Response("done") ''' -
Open external website from a Django website and login user to that external website
I have a button on my Django website with the label 'Open Website' which opens up a website login page in the next tab. I have the username and password for the website and I want to log in the user to the next website programmatically (like I have to enter password and username and click on the login button). What I have tried is: I used selenium but it's opening the browser on my side and entering username and password and clicking on the login button but it's not opening the browser on the client side. -
Inherit multiple Django choices classes in one choices class
Let's say we have two choices classes in Django like: from django.db import models class C1(models.TextChoices): attr1 = "ATTR1", "Attr 1" attr2 = "ATTR2", "Attr 2" class C2(models.TextChoices): attr3 = "ATTR3", "Attr 3" attr4 = "ATTR4", "Attr 4" And we need to inherit these two classes in one choices class like this: class C(C1, C2): pass It throws an error like this: TypeError: C: cannot extend enumeration 'C1' -
Use two different views in the same url path in django
I got two views. First one list some reports per user in a sidebar Second one shows the report in Power BI using embedded code The thing how can I use both views in one template. THe problem is if I put the path of the first view I can't see the report slected (second view), and vice versa. Here I'll show images I'll add some code below views.py #List reeports per user in the sidebar def insertar(request): usuario = Usuario.objects.get(username=request.session['username']) reportes = Reporte.objects.filter(id_usuario=usuario.id_usuario) return render(request, 'base.html', {'reportes': reportes}) #Shows the report selected using Powe BI def reportes(request, titulo): usuario = Usuario.objects.get(username=request.session['username']) reporte = Reporte.objects.get(titulo=titulo, id_usuario=usuario.id_usuario) return render(request, 'reporte.html', {'reporte': reporte}) urls.py urlpatterns = [ path('home', views.insertar, name='index'), re_path(r'^home/.*$', views.insertar, name='index'), path('home/<titulo>', views.reportes, name='reporte'), ] base.html <body> <div class="sidenav"> {% include "sidebar.html" %} </div> <div class="main"> {% block content %} {% endblock %} </div> </body> reporte.html {% extends "base.html" %} {% block title %} Listado de Reportes {% endblock %} {% block content %} <iframe title="{{reporte.titulo}}" width="1024" height="612" src="{{reporte.link}}" frameborder="0" allowFullScreen="true"> </iframe> {% endblock %} sidebar.html {% for i in reportes %} <a href="/home/{{i.titulo}}" class="d-block text-light p-3">{{ i.titulo }}</a> {% endfor %} -
Django case insensitive search in multilevel jsonb field using ORM methods
here is my sample jsonb field: { "name": "XXXXX", "duedate": "Wed Aug 31 2022 17:23:13 GMT+0530", "structure": { "sections": [ { "id": "0", "temp_id": 9, "expanded": true, "requests": [ { "title": "entity onboarding form", # I need to lookup at this level (or key) "agents": [ { "email": "ak@xxx.com", "user_name": "Akhild", "review_status": 0 } ], "req_id": "XXXXXXXX", "status": "Requested" }, { "title": "onboarding", # I need to lookup at this level (or key) "agents": [ { "email": "adak@xxx.com", "user_name": "gaajj", "review_status": 0 } ], "req_id": "XXXXXXXX", "status": "Requested" } ], "labelText": "Pan Card" } ] }, "Agentnames": "", "clientowners": "Admin", "collectionname": "Bank_duplicate" } In this json i need to do case insensitive match for structure->section->request(array)-> title inside each object of request array I have tried this query filter (Q(requests__structure__sections__contains=[{'requests':[{"title": query}]}])) but it becomes case sensitive. Also i have tried self.get_queryset().annotate(search=SearchVector(Cast('requests__structure__sections', TextField())) which does gives case insensitive result but also lookup among the keys other than title. also i tried raw sql where i cannot go beyond the request array. Im expecting any other method or any other approach in django orm that can be used to achieve the require result. -
Multiple htmx hx-target
I have 3 select fields CATEGORY—-->SUBCATEGORY_1 > | > —>SUBCATEGORY_2 Is it possible to update both subcategories when I change CATEGORY value? . I know how to make simple category to subcategory relation , but can’t figure out how to expand it for 2 and more subcategories What I should use to achieve this functionality? -
Django Chat App - Can't automatically scroll down live chat box when new messages are added
So I'm making a chat app with Django Channels, Javascript, and HTML/CSS. I am really not that familiar at all with front-end but so far everything seems to be working fine with my chat app except for the chat box itself not moving downwards when new messages are added. I set my CSS .chatbox class to have an overflow: scroll, but adding that won't make the box auto-scroll when new messages are inserted. I assume based on research I need to alter my javascript script but I honestly don't know where to start. Again, please go slow with me lol I'm not really familiar with frontend. Current Javascript: <script> const chatLog = document.querySelector('#chat-log'); const chatSocket = new WebSocket("ws://" + window.location.host + "/"); if (!chatLog.hasChildNodes()) { const emptyText = document.createElement('h3') emptyText.id = 'emptyText' emptyText.innerText = 'No Messages' emptyText.className = 'empty Text' chatLog.appendChild(emptyText) }; chatSocket.onopen = function (e) { console.log("The connection was setup successfully !"); }; chatSocket.onclose = function (e) { console.log("Something unexpected happened !"); }; document.querySelector("#id_message_send_input").focus(); document.querySelector("#id_message_send_input").onkeyup = function (e) { if (e.keyCode == 13) { document.querySelector("#id_message_send_button").click(); } }; document.querySelector("#id_message_send_button").onclick = function (e) { var messageInput = document.querySelector("#id_message_send_input"); message = messageInput.value; chatSocket.send(JSON.stringify({ message: message, username : "{{request.user.username}}"})); messageInput.value = ""; }; …