Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, Django: ForeignKey with dependencies (models.py)
Good day, I would like to ask, if it's possible to determine an additional dependencie on a models.ForeignKey-field? For example ... models.py class Object_A(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) date_created = models.DateTimeField(auto_now_add=True) class Object_B(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) object_a = models.ForeignKey(Object_A, null=False, blank=False, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) class Object_C(models.Model): name = models.Charfield(max_length=50, null=False, blank=False, unique=True) object_a = models.ForeignKey(Object_A, null=False, blank=False, on_delete=models.CASCADE) object_b = models.ForeignKey(Object_B, null=False, blank=False, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) forms.py class Create_Object_C_Form(ModelForm): class Meta: model = Object_C exclude = [ 'object_a', 'date_created', ] What I'm trying to do... As you can see, I'm excluding the object_a, because at this point inside my app where the form is used, the user doesn't have to choose for an object_a. His own steps have anticipated this choice! The same - or at least almost the same - goes for object_b: Is it possible to only show choices that are related to the same object_a? Hoping I could explain my problem understandably and somebody can help or has an idea!? Have a great day! -
Not able to post the form
So i have a table in ms sql database.the connections is open but the form wont submit. def add(request): print('start') if request.method == "POST": print('post') if request.POST.get('name') and request.POST.get('contact_person') and request.POST.get( 'address') and request.POST.get('ph_no') and request.POST.get('tele') and request.POST.get( 'mail') and request.POST.get('is_active') and request.POST.get('last_update'): print('get') insertstvalues = Company() # insertstvalues.company_id = request.POST.get('company_id') insertstvalues.name = request.POST.get('name') insertstvalues.contact_person = request.POST.get('contact_person') insertstvalues.address = request.POST.get('address') insertstvalues.ph_no = request.POST.get('ph_no') insertstvalues.tele = request.POST.get('tele') insertstvalues.mail = request.POST.get('mail') insertstvalues.is_active = request.POST.get('is_active') # insertstvalues.last_update = request.POST.get('last_date') print('values') cursor.execute( "insert into Company values ('" + insertstvalues.name + "','" + insertstvalues.contact_person + "','" + insertstvalues.address + "','" + insertstvalues.ph_no + "','" + insertstvalues.tele + "','" + insertstvalues.mail + "','" + insertstvalues.is_active + "')") print('execute') cursor.comit() print('record added') return render(request, 'addRecord.html') else: print('Rerun') return render(request, 'addRecord.html') this is the functions i have in views.py.connections and cursor strings are all working. here is the html code for the from to take in the values so when i run the app this is what i see cmd terminal after i click the insert button basically as far as i can see is that the program never runs the second if statement. I want to add data to my table so i am open to any … -
How to update primary key, what have foreign keys pointing to, without "ON UPDATE CASCADE"
I have PostgreSQL database created with Django with lots of tables. Also there are multiple foreign keys between tables. I need to change id (primary key) field of users_user table, but there are a lot of tables that are pointing to it. Of course ideal solution is to add "ON UPDATE CASCADE" to all of the foreign keys. But in my case its impossible during long sequence of reconciliations, making agreements with other teams about such database model changes. So, I need a way of changing primary key and all the foreign keys automatically without manually specifying other tables, because there are a lot of. -
why i cant save student data in database using Django
when I'm trying to save the attendance of students but is not saving data in the database. it's giving an error in of else which I coded in the views.py file. I have taken name,rollnumber from studentProfile, and status from studentAttendance and trying to save in the database but I'm getting an error message which I have coded in views.py. views.py from django.contrib import messages from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from .forms import * from .models import * def studentAttendanceView(request): student_status = studentProfile.objects.all() if request.method == "POST": studentData = studentAttendanceForm(request.POST) if studentData.is_valid(): cd = studentData.save() cd.author = request.user cd.save() cd.refresh_from_db() name = studentData.cleaned_data.get('name') messages.success(request, f'Attendance submitted for {name} ') else: messages.error(request, 'Please check An Error occurred') else: studentData = studentAttendanceForm() return render(request, 'attendance.html', {'studentData': studentData, 'student_status': student_status}) forms.py from django import forms from .models import * class studentAttendanceForm(forms.ModelForm): class Meta: model = studentAttendance fields = ['name', 'status'] class studentProfileForm(forms.ModelForm): class Meta: model = studentProfile fields = '__all__' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.studentProfileView, name='studentProfile'), path('attendance/', views.studentAttendanceView, name='studentData'), ] models.py from django.db import models class studentProfile(models.Model): name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(unique=True) rollNumber = models.IntegerField(unique=True) class … -
How to import vue component in Django template script
according to the following component document https://talkhabi.github.io/vue-persian-datetime-picker/#/installation Need to import import VuePersianDatetimePicker from 'vue-persian-datetime-picker' But I do not know how to address to read the file from static files How do I address? 'vue-persian-datetime-picker' -
Implementing push notification in flutter with django channels and django REST framework
I'm working on a flutter based chat app of an existing web app built in Django. I'm using django channels for the messaging and notifications in website. I've successfully implemented messaging using websockets in mobile app but unable to implement push notifications when app is closed i.e. no websocket connection established. How to implement this? Thanks in advance :) -
JsonResponse print dictionary instead of return to ajax success function in django
here i want to give a Javascript alert when data is insert into database. data is successfully into database, but JsonResponse not return dictionary to ajax success function and print data of dictionary into webpage. here i put only ajax part of my html file HTML File $.ajax({ type: 'POST', url: '{% url 'Patient:add' %}', data: info, dataType: 'json', success: function (data) { console.log("Received") if (data.saved === 1) { alert("Data Saved"); } } }); This is my view.py code def add_patient(request): if request.method == 'POST': name = request.POST['name'] gender = request.POST['gender'] birthdate = request.POST['birthdate'] add = Patient(name=name, gender=gender, birthdate=birthdate) add.save() data = {'saved': 1} return JsonResponse(data) else: return render(request, 'Patient_template/add_patient.html') here i call ajax function on form submit event using javascript, when i fill all filed and submit the form it redirect to the web page, which show {'saved': 1}. screenshot of page after submit the form here -
Django - export excel make it faster with openpyxl
I am using Django restframework and I am trying to export excel. My issue is the process is take a lot of time till it generates the excel file. The final file have about 1MB with 20k lines and the generation time is about 8 minutes and this does not seem right. here is the view: class GenerateExcelView(APIView): filename = 'AllHours.xlsx' wb = Workbook() ws = wb.active ws.title = "Workbook" data = Report.objects.all() row_couter = 2 for line in data: first_name = line.employee_id second_name = line.employee_name age = line.description ... ws['A{}'.format(row_counter)] = first_name ws['B{}'.format(row_counter)] = second_name ws['C{}'.format(row_counter)] = age ... row_counter +=1 response = HttpResponse(save_virtual_workbook(wb), content_type='application/ms-excel') response["Content-Disposition"] = 'attachment; filename="' + filename + '"' return response There are few more columns... Is it possible to change the process so it is a bit faster? -
How to create an overview API for statistics with the Django REST framework
Currently, I have such a view and serializer, but how can I create an overview API for statistics? serializers.py class ExampleSerializer(serializers.ModelSerializer): total = serializers.SerializerMethodField() class Meta: model = Example fields = '__all__' def get_hms(self, obj): return Example.objects.count() views.py class ExampleViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] serializer_class = ExampleSerializer def get_queryset(self): return self.request.user.example.all() def perform_create(self, serializer): serializer.save(user=self.request.user) total = serializers.SerializerMethodField() is used to display the number of Examples, but with this code, only one is needed since it is originally an overview, but the total is displayed as many as there are models. How can I create a View and Serializer that is not associated with a model? I would appreciate it if you could tell me more. -
Displaying several rows of text from a view in Django
I am working on a Django application that displays information recorded in user logs. This specific one is designed to tell which users share an IP. My Code looks like this: users = logs.username.unique() UsedUsers = [] print('Shared IPs:') print() for user in users: UsedUsers.append(user) for otherplayer in users: if otherplayer not in UsedUsers: Userlogs = logs[logs.username.isin([user]) UserIP = Userlogs.IP.unique() OtherPlayerlogs = logs[logs.username.isin([otherplayer]) OtherPlayerIP = OtherPlayerlogs.IP.unique() SharedIPs = set(UserIP).intersection(OtherPlayerIP) print(user, 'shares these IPs with', otherplayer, ":") print(*SharedIPs, sep = "\n") print() Naming conventions are probably pretty bad. This is more of my learning project. My issue is that I can get this code to work in Juypter Notebook, but when I switch it to a view in Django I am not sure how to store it to pass it into a .html -
Python get max price sum 3 top records
I have a table where data like : Id price date user_id type __________________________________________________________________ 1 120 2021-03-05 1 credit 2 120 2021-03-05 1 credit 3 120 2021-03-08 2 credit 4 120 2017-06-20 3 credit 5 140 2017-06-20 4 debit 6 120 2017-06-20 1 credit 8 120 2021-03-09 2 credit 9 130 2017-06-20 2 credit 10 120 2021-03-05 1 debit 11 160 2021-03-05 5 debit 12 210 2021-03-05 5 credit what i actually want is i want distinct user according to userid and created_at between 2021-03-05 to 2021-03-11 with type credit 3 top price users with price sum . 3 top user which have max price sum according to this filter. i am stuck here can anyone please help me related this ?? -
How to get request obj in @reciver post_save in django?
@receiver(post_save, sender=Enrollment) def update_cert_qual_progress(sender, instance, created, **kwargs): if not created and "progress" in instance.changed_fields: if instance.certification_id: certification_progress = Enrollment.objects.filter( user=instance.user, certification=instance.certification ).aggregate(Avg("progress")) CertificationUser.objects.filter( user=instance.user, certification=instance.certification ).update(progress=certification_progress["progress__avg"]) if instance.status == "completed": certification = course_user_item.course.uuid get_or_create_user_certification_certificate(request, certification) if instance.qualification_id: qualification_progress = Enrollment.objects.filter( user=instance.user, qualification=instance.qualification ).aggregate(Avg("progress")) QualificationUser.objects.filter( user=instance.user, qualification=instance.qualification ).update(progress=qualification_progress["progress__avg"]) i have to call below function in above code,but for that i need request object .But i am not able to fetch request object . def update_cert_qual_progress(sender, instance, created, **kwargs): if not created and "progress" in instance.changed_fields: if instance.certification_id: certification_progress = Enrollment.objects.filter( user=instance.user, certification=instance.certification ).aggregate(Avg("progress")) CertificationUser.objects.filter( user=instance.user, certification=instance.certification ).update(progress=certification_progress["progress__avg"]) if instance.status == "completed": certification = course_user_item.course.uuid get_or_create_user_certification_certificate(request, certification) if instance.qualification_id: qualification_progress = Enrollment.objects.filter( user=instance.user, qualification=instance.qualification ).aggregate(Avg("progress")) QualificationUser.objects.filter( user=instance.user, qualification=instance.qualification ).update(progress=qualification_progress["progress__avg"]) Please suggest something how to solve this and help me. -
modal window in django template using HTMX
I have a template and a modal window inside it. Normally (with JS only) I would have some code in the template that toggles the modal: {% include "testapp/modal/test_modal.html" %} <button class="..." data-toggle="modal" data-target="#testModal"></button> and add a test_modal.html file in my templates folder which contains the modal window: <div class="modal ..." id="testModal" aria-hidden="true"> .... <button id="test_submit" type="submit"></button> <!-- submit modal --> </div> A simple JS line would select what happens on pressing the button: document.querySelector('#test_submit').addEventListener('click', event => { $('#testModal').modal("hide") const dlwindow = window.open(`/test/${testvar}`, "_self"); which would trigger some view defined in the urls.py by django: path(r"test/<testvar>", views.TestView.as_view(), name="test") So far, so good. Now I want to create the same setup using HTMX and when following the HTMX modal exmaple I come to the point where the example says: <button hx-get="/modal" hx-target="#modals-here" hx-trigger="click" class="btn btn-primary" _="on htmx:afterOnLoad wait 10ms then add .show to #modal then add .show to #modal-backdrop">Open Modal</button> <div id="modals-here"></div> This button uses a GET request to /modal when this button is clicked. The contents of this file will be added to the DOM underneath the #modals-here DIV. This is exactly where I am stuck: The GET request should point to a urls.py entry, aka a view of some … -
Expose page alias in wagtail API
Wagtail recently gained support for page aliases (the same page in another part of the tree). The API returns these pages as if they are "normal" pages. I'd like the API to tell me that the page is an alias of another page. The reason for this is to be able to add a rel="canonical" link. I'd also like to be able to (optionally) return the list of aliases for the original page using the API. This way I can build a list of "this page is also available here". It seems that it is possible to detect an aliases by inspecting the alias_of ForeignKey: https://github.com/wagtail/wagtail/blob/c5f49274c8730ce04ca76df1ceef96d5cc83fac0/wagtail/core/models.py#L843 But I'm unsure on how to make this work with the Wagtail API and DRF serializers. -
Django how to add double filter in admin page add model(foreign field items)
class BodyPart(models.Model): name = models.CharField(max_length=100) class Exercise(models.Model): name = models.CharField(max_length=200) body_part_primary = models.ForeignKey(BodyPart, on_delete=models.CASCADE) class ExerciseTracker(models.Model): time = models.DateField(auto_now_add=True) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) In the above code, the Excercise model includes the BodyPart model as a foreign key. While adding a new ExerciseTracker entry on the admin page it shows a drop-down of the foreign key. But How to add a filter for exercise based on BodyPart in ExerciseTracker? So that the field is a double dropdown -
how to get multiply two columns of a row in formset django?
i'm working on a project which admins can write make invoice , every invoice contains several items with different quantities and prices , in order to give right total price i have to make some calculation in the template before save it ! i've made the template and it works fine , but whenever i try to use inlineformset in django , it doesnt make the calculation this is my template {% extends 'base.html' %} {% load widget_tweaks %} {% load static %} {% block title %} create new invoice {% endblock %} {% block content %} <form method="POST">{% csrf_token %} {{items.management_form}} <div class="w-full md:w-11/12 mx-auto realative p-2 bg-gray-200 invoice" style="direction: ltr !important;"> <div class="p-1 pr-2 pb-1 text-xs border border-black rounded-lg flex flex-wrap"> <div class="flex w-8/12 lg:w-9/12"> <div class="w-10/12 ml-8 border-b border-gray-600 border-dotted"> {{form.customer | add_class:'bg-transparent w-full text-right focus:outline-none'}} </div> <div class=""> : ناو </div> </div> </div> <!-- table --> <div class="mt-1 border border-black"> <!-- header --> <div class="flex flex-wrap grayBG text-sm text-white"> <div class="w-1/12 text-center border-r"> <i class="fas fa-cog"></i> </div> <div class="w-2/12 border-r text-center"> total price </div> <div class="w-2/12 border-r text-center"> discount </div> <div class="w-1/12 border-r text-center"> cash </div> <div class="w-1/12 border-r text-center"> loan </div> <div class="w-1/12 border-r text-center"> … -
Jquery autocomplete two fields doesn't work
I'm using jquery to autocomplete form field in django template. Problem is, after adding second function both of them aren't working. How to write it properly? var cities = {{cities|safe}}; $( function() { $("#id_city").autocomplete({ source: cities, }); var categories = {{categories|safe}} $( function() { $("#id_category").autocomplete({ source: categories, }); -
Django Rest Framework and existing forms
I have an existing application with some rather complicated forms already written. I'm asked to add an API (will be using Django-Rest-Framework) for a lot of those forms. Is there any way to cleanly use the existing forms I have to validate the Serializers using the existing forms validation I've already written ? According to the documentation, DRF uses an entirely different validation system that the one I currently have (form validation and model validation). I do not want to write the same validation twice (one for the API, other for the Serializers). I'm thinking of submitting the forms in the ModelSerializer.validate method, but this feels more of dirty hack than clean development to me since DRF does seems to want to be decoupled from Django form system. Any idea on this ? -
Inserting 200 rows of dataframe in the Django models takes like 7 seconds. Is there anyway i can speed up the process?
for transaction in df.itertuples(): transaction_obj = Transactions() transaction_obj.portfolio = strategy.portfolio transaction_obj.strategy = strategy transaction_obj.transaction_price = transaction.TransactionPrices transaction_obj.time_stamp = transaction[0] transaction_obj.transaction_type = name transaction_obj.brokerage = transaction.Brokerage if name == Transactions.LONG: if transaction.EntryLong: transaction_obj.action = Transactions.BUY if transaction.ExitLong: transaction_obj.action = Transactions.SELL elif name == Transactions.SHORT: if transaction.EntryShort: transaction_obj.action = Transactions.SELL if transaction.ExitShort: transaction_obj.action = Transactions.BUY transaction_obj.save() my code here works all fine with no problem. I just want to reduce the execution time. Currently it takes like 7 seconds to insert around 180 lines of row. I am using "Postgresql" database -
Stream framework with django redis celery
I have followed stream framework conf but still getting error like int has no items , pinmanager is not json serialised can any one say version of redis ,celery and conf setting so that i can setup -
unable to query for a specific "user subscription" in django
I'm creating a django ecommerce site; This site "sells" digital items. I'm unable to fetch a specific " user subscription", meaning a user has bought this digital item and I want to display it in a template. in this case I'm interested in displaying the "plan_name" (from subscription model), "created_date" and "expiry_date" in the template for a specific user but somehow I'm unable to. Hereunder the code: models.py class Subscription(models.Model): plan_name = models.CharField(max_length=50, null=True, blank=True, verbose_name="Subscription Plan Name") description = models.TextField(verbose_name="Subscription Plan Description") price = models.FloatField(verbose_name="Subscription Plan Price") start_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Subscription Plan Start Date") end_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Subscription Plan End Date") active = models.BooleanField(default=False) class Meta: verbose_name = "Subscription" verbose_name_plural = "Subscriptions" def __str__(self): """Unicode representation of Subscription""" return " Subscription type: {}, Description: {}, Price: {}, Is active: {}".format( self.plan_name, self.description, self.price, self.active ) class UserSubscription(models.Model): user = models.ForeignKey(User, related_name= 'tosubscriptions', on_delete=models.CASCADE, null=True, blank=True) subscription = models.ForeignKey("Subscription", related_name = 'tosubscriptions',on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True, verbose_name="Created Date") expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False, verbose_name="Expiry Date") is_canceled = models.BooleanField(default=False, verbose_name="Is Canceled") cancel_date = models.DateTimeField(auto_now=False, auto_now_add=False, blank=True, null=True) class Meta: verbose_name = "User Subscription" verbose_name_plural = "User Subscriptions" def __str__(self): """Unicode representation of UserSubscription""" return "PK: [{}] Subscription of: {}, … -
MultiValueDictKeyError at /api/register/ Django API
I'm trying to connect my API to my frontend so I have read about Ajax but it receive this error. My API work perfectly on Postman. My URL for this API is http://127.0.0.1:8000/api/register/. File "C:\Users\vinhv\Dropshipping-e-commercial-website\home\views.py", line 176, in post password = user["password"] Django 3.1.4 Python 3.8.2 Here is my API view: class RegisterView(generics.GenericAPIView): serializer_class = AccountRegisterSerializer def post(self, request): user = request.data password = user["password"] salt = bcrypt.gensalt() # Generate a salt for hashing password hashed = bcrypt.hashpw(password.encode('utf8'),salt) user["salt"] = salt.decode("utf8") user["password"] = hashed.decode("utf8") serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data del (user_data['salt']) return Response(user_data, status=status.HTTP_201_CREATED) Here is my HTML: <div class="col-lg-6 col-md-6"> <div class="account_form register" data-aos="fade-up" data-aos-delay="200"> <h3>Register</h3> <form action="http://127.0.0.1:8000/api/register/" method="post"> {% csrf_token %} <div class="default-form-box mb-20"> <label>Email address <span>*</span></label> <label> <input type="text" id="email"> </label> </div> <div class="default-form-box mb-20"> <label>Username<span>*</span></label> <label> <input type="text" id="username"> </label> </div> <div class="default-form-box mb-20"> <label>Passwords <span>*</span></label> <label> <input type="password" id="password"> </label> </div> <div class="register_submit"> <button id="register_btn" type="submit" value="register">Register</button> </div> <script> $('#register_btn').click(function () { var email = $('#email').val(); var username = $('#username').val(); var password = $('#password').val(); console.log(email); console.log(username); console.log(password); var form = $(this).closest("form") $.post({ url: "http://127.0.0.1:8000/api/register/", data: user, dataType:'json', success: function (response) { if(response == '201'){ console.log("Register Success") }else{console.log("Email already exist") } } });}) … -
Django channels working with WS:// but not with WSS://
I followed explanations from django-channels tutorial and was able to run a chat locally. However, it does not work in production. Here is the output from debugger : WebSocket connection to 'wss://www.example.com/ws/chat/lobby/' failed: Error during WebSocket handshake: Unexpected response code: 404 (anonymous) @ (index):23 (index):40 Chat socket closed unexpectedly chatSocket.onclose @ (index):40 (index):56 WebSocket is already in CLOSING or CLOSED state. document.querySelector.onclick @ (index):56 document.querySelector.onkeyup @ (index):47 Here is the javascript I use to try having it work with our https website : const roomName = JSON.parse(document.getElementById('room-name').textContent); var loc = window.location; var wsStart = 'ws://'; if (loc.protocol === 'https:') { wsStart = 'wss://' } const chatSocket = new WebSocket( wsStart + window.location.host + '/ws/chat/' + roomName + '/' ); I use redisgreen for redis : CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('redis://:xxxxxxx@great-whale-0077a76ca7.redisgreen.net:11042/')] }, }, } The rest of the code is as per the tutorial. I am not sure how I should address this issue. Any clue ? Is it required to implement Daphne to run channels in production ? Or did I do something wrong ? Thanks a lot for your help. -
Django rest and ManyToMany through model
I'm trying to build a basic CRUD api that will return the nutrients of a recipe. models.py class Ingredient(models.Model): name = models.CharField(max_length=100) kcal = models.FloatField(null=True) carb = models.FloatField(null=True) sugar = models.FloatField(null=True) protein = models.FloatField(null=True) class Recipe(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(User, related_name="recipes", on_delete=models.CASCADE, null=True) ingredients = models.ManyToManyField(Ingredient, through='RecipeIngredient', blank=True) class RecipeIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) amount = models.FloatField(null=True) The basic functionality of creating and viewing ingredients and recipes is already implemented, but how do I implement the many-to-many relationship including the ingredient amount into serializers, views and urls? And maybe as a bonus; how does the http request look like to test that functionality? Even a nudge towards the right literature would be much appreciated, thanks in advance. -
Replacing response output messages with some code(say Msg007) and translate them when we hit api in django
I need each of my API method output messages into some code(say Msg112) and all those codes should be in single file. And I should replace those output messages with that code. And if I hit some API, the relevant output message should come as translated message. I tried using django-admin makemessages and compile messages command but this is not working.