Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter and order by with Sum while keeping the summed data in Django
OK..I even do not know how to describe the situation in the title. But considerate below models: class TheModel(models.Model): qty = models.IntegerField() name = models.CharField() type = models.CharField(choices=['A' ,'B', 'C']) The requirement is to get the sum of qty and sort by sum of qty, but also has sum of A, B, C. assume there are 5 rows in total: name, qty, type (name1, 3, A) (name1, 3, B) (name1, 4, C) (name2, 5, A) (name2, 10, C) The result should be like this: name sum_qty, type A, type B, type C name1 10 3 3 4 name2 15 5 0 10 -
Best practices for authenticating Django Channels
Django 4.1.4 djoser 2.1.0 channels 4.0.0 I have followed the documented recommendation for creating custom middleware to authenticate a user when using channels and I am successfully getting the user and checking that the user is authenticated though I am sending the user ID in the querystring when connecting to the websocket to do this. The user is not automatically available in the websocket scope. I am unsure if there are any potential security risks as the documentation mentions that their recommendation is insecure, I do check that the user.is_authenticated. So I believe I have secured it. I do believe that using the token created by djoser would be better though I am not sure how to send headers with the websocket request unless I include the token in the querystring instead of the user's ID. I am keen to hear what the best practices are. I am passing the user ID to the websocket via querystring as follows at the frontend: websocket.value = new WebSocket(`ws://127.0.0.1:8000/ws/marketwatch/? ${authStore.userId}`) middleware.py from channels.db import database_sync_to_async from django.contrib.auth.models import AnonymousUser from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist @database_sync_to_async def get_user(user_id): User = get_user_model() try: user = User.objects.get(id=user_id) except ObjectDoesNotExist: return AnonymousUser() else: if … -
IntegrityError at /station/Add/ (1048, "Column 'user_type_id' cannot be null")
I'm trying to create new station using generic views when i try without user_type forigen key I received this error IntegrityError at /station/Add/ (1048, "Column 'user_type_id' cannot be null") if i tried without user_type and submit button cilck form automatic refresh and same clean Here is my code: station/views.py class StationCreateView(LoginRequiredMixin, CreateView): model = Station fields = ('station_name', 'station_address','connectors','status', 'start_time','end_time','open_day', 'state', 'city', 'area', 'user_type') template_name = 'owner/add_station.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) here is my code: add_station.html <form method="post" action="" novalidate> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.station_name|as_crispy_field }} </div> <div class="form-group col-md-12 mb-0"> {{ form.station_address|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.connectors|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.status|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.start_time|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.end_time|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.open_day|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.state|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.city|as_crispy_field }} </div> <div class="form-group col-md-6 mb-0"> {{ form.area|as_crispy_field }} </div> <button type="submit" class="w-full rounded-full bg-red-gradient p-3 text-white font-bold hover:ring">Add Station</button> </div> </form> -
HOW TO OUTPUT DATA GOT FROM combined queryset IN DJANGO TEMPLATE (html file)?
Am having a problem. And l request for your Help. Am having 3 apps in Django project action adventure others `#action/ models.py .... class Action(models.Model): name=models.Charfield() os= models.Charfield( choices=OS).... #adventure/models.py .... class Adventure(models.Model): name=models.Charfield() os= models.Charfield( choices=OS).... #Others/views.py from itertools import chain from action.models import Action from adventure.models import Adventure def windows_games(request): win_action = Action.objects.filter(os='windows') win_adventure = Adventure.objects.filter(os='windows') combined_list = list(chain(win_action,win_adventure)) context = ['combined_list':combined_list,] return render(request, 'others/os/windows_game.html' , context) #others/os/windows_game.html ..... {{combined_list.name}} 1). I need to correct me in #others/ views.py if there is any mistake done. 2). I would like to know how to know how to write the tag that outputs the results in #others/os/windows_game.html because I tried that but outputs nothing. And l would like to be in form of, #{{combined_list.game_pic}}, etc It needed to display all items created in those models to display in windows_game page, after filtering those that only follow in category of windows. I tried creating the context but there was no output results. -
Django ModelChoiceField with custom queryset not validating
My ModelChoiceField is not validating saying that the selected choice is not an instance. I am passing a custom queryset to my modelChoiceField that uses a custom manager (objects_sys) to return extra entries that are archived and do not normally display with normal queries. The entries are displayed and I can select them, but when the form posts and Django tries to validate, it must be using another query that filters out the archived items so those are not valid choices. I'm using class based views - this vails in form_valid() Models: class Item(models.Model): name = UpperCaseCharField(max_length=10, primary_key=True) description = models.CharField(max_length=200) class ItemLoc(models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) location = models.CharField(max_length=200) My Form: class ItemForm(forms.ModelForm): class Meta: model = ItemLoc fields = ( 'item', 'location' ) def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['item'].queryset = Items.objects_sys.filter(qty_on_hand__gt=0) Do I need to pass this custom query in again to the ModelChoiceField at some point so that the extra values are available for validation? Thank you for your help -
Django select_related returning empty query set if the PK deleted from other table
Consider I am having a table that having a foreignkey relation with the user model. class MyModel(models.Model): created_user = models.ForeignKey(settings.AUTH_USER_MODEL) I am taking queryset like this qs = MyModel.objects.select_related('created_user').all() This query working fine , but if the user deleted from the database, then it is showing empty queryset. -
how to improve the reading time of files in an S3 bucket from Django?
I have a process in which I have to read several files from S3 to show them in a report. list_images = Inspection_File.objects.filter(inspection_id=inspection.pk).order_by('category__name') for image in list_images: image_data = image.file.read() #this process is very slow list_img.append({'file': img}) Analyzing the code I saw that the process of reading the file from the model is one that takes a long time, about 20 images take approximately 20 seconds, which is too long to wait, I understand that they are images, however, these images weigh less than 1MB, any ideas to improve the response time? -
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 …