Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django generate thumbnail of view
I want to generate a thumbnail image for my static view. for example, I have a view: def exampleView(request): return HttpResponse('<h1>here</h1>') How can I get an image of a blank page with a here title? It may sounds like a non-sense feature request, but I really need it to achieve my app functionality, I will be so grateful for any suggestion you make. -
Initial values, initialized using JS, not changing while updating data in Django Model Form
models.py class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) Based on the treatment and patient_type, I want max_fractions and total_package to be given initial values. For that I wrote a JS function: function mf(){ tt_select = document.getElementById("id_package_form-treatment"); tt = tt_select.options[tt_select.selectedIndex].text; ptt_select = document.getElementById("id_package_form-patient_type"); ptt = ptt_select.options[ptt_select.selectedIndex].text; max = document.getElementById("id_package_form-max_fractions"); if (tt=="MVTR" && ptt=="JTCPR") max.value=40; else if (tt=="MVTR" && ptt=="JTCPR/PC") max.value=40; else if (tt=="MVTR" && ptt=="CASH") max.value=40; else if (tt=="CRFP" && ptt=="JTCPR") max.value=40; else if (tt=="CRFP" && ptt=="JTCPR/PC") max.value=40; else if (tt=="CRFP" && ptt=="CASH") max.value=40; else if (tt=="5DTYU" && ptt=="JTCPR") max.value=30; else if (tt=="5DTYU" && ptt=="JTCPR/PC") max.value=30; else if (tt=="5DTYU" && ptt=="PMJAY") max.value=30; else if (tt=="5DTYU" && ptt=="CASH") max.value=30; else if (tt=="FRTC" && ptt=="JTCPR") max.value=40; else if (tt=="FRTC" && ptt=="JTCPR/PC") max.value=40; else if (tt=="FRTC" && ptt=="PMJAY") max.value=30; else if (tt=="FRTC" && ptt=="CASH") max.value=35; else if (tt=="PALLATIVE" && ptt=="JTCPR") max.value=10; else if (tt=="PALLATIVE" && ptt=="JTCPR/PC") max.value=10; else if (tt=="PALLATIVE" && ptt=="CASH") max.value=5; else if (tt=="RADICAL" && ptt=="JTCPR") max.value=0; else if (tt=="RADICAL" && ptt=="JTCPR/PC") max.value=0; else if (tt=="RADICAL" && ptt=="CASH") max.value=0; else if (tt=="ADJUVANT" && ptt=="JTCPR") max.value=0; else if (tt=="ADJUVANT" && ptt=="JTCPR/PC") max.value=0; else if (tt=="ADJUVANT" && ptt=="CASH") max.value=0; else max.value=0 } function tp(){ tt_select = document.getElementById("id_package_form-treatment"); … -
How to access properties of foreign key in csv file, django
views.py properties = [ 'first_name', 'policy__request' # Here I want to access the request of policy ] for row_num, model in enumerate(Model.objects.all()): for col_num, property in enumerate(properties): ws.write(row_num+1, col_num, getattr(model, property), font_style) I got the following error 'Model' object has no attribute 'policy__request' I'm trying to create a csv file with my data frmo database and I want to have access the properties of the foreign key -
Django PIPE youtube-dl to view for download
TL;DR: I want to pipe the output of youtube-dl to the user's browser on a button click, without having to save the video on my server's disk. So I'm trying to have a "download" button on a page (django backend) where the user is able to download the video they're watching. I am using the latest version of youtube-dl. In my download view I have this piece of code: with youtube_dl.YoutubeDL(ydl_opts) as ydl: file = ydl.download([f"https://clips.twitch.tv/{pk}"]) And it works, to some extend. It does download the file to my machine, but I am not sure how to allow users to download the file. I thought of a few ways to achieve this, but the only one that really works for me would be a way to pipe the download to user(client) without needing to store any video on my disk. I found this issue on the same matter, but I am not sure how to make it work. I successfully piped the download to stdout using ydl_opts = {'outtmpl': '-'}, but I'm not sure how to pipe that to my view's response. One of the responses from a maintainer mentions a subprocess.Popen, I looked it up but couldn't make out … -
How to insert the data that is returned from an API in a text format to the Django models
I'm using an API (https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/Tmax/date/UK.txt) that returns the data in a text format. so with the data returned I want to add those data in the Django model. so Now I'm stuck with the problem that how should I parse the data in order to add them to the model. Because since the data returned by that API as you can see that the year 2021 doesn't have all the data. Currently, I have 18 fields in the Django model (each field for each value) and my approach was to extract all the data which has a numerical constant pattern using regex and with the extracted data, I will insert the data into the DB model by iterating it over the list. But the problem is that year 2021 doesn't have all the data and the regex that I'm using is just extracting the numerical values from the string that is returned from the API. for example: ear jan feb mar apr may jun jul aug sep oct nov dec win spr sum aut ann 2021 4.9 7.0 9.8 10.9 13.4 18.7 21.1 18.9 18.7 14.0 6.21 11.35 19.56 code that I've written so far. numeric_const_pattern = '[-+]? (?: (?: … -
How to make a local form to stored in Django admin
Hi there i tried for make Django project and make a local form to stored in django admin here is my "view" code from django.http import request from django.shortcuts import render,redirect from templates.forms import Registrationform from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm def home(request): numbers = [1,2,3,4,5] name = 'max' args = {'myName': name,'numbers':numbers} return render(request, 'accounts/home.html',args) def register(request): if request.method == 'POST': form = Registrationform(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = Registrationform() args = {'form':form} return render(request,'accounts/reg_form.html',args) def view_profile(request): args ={'user':request.user} return render(request,'accounts/profile.html',args) def edit_profile(request): if request.method == 'POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/account/profile') else: form = UserChangeForm(instance=request.user) args={'form':form} return render(request,'accounts/edit_profile.html') error: from templates.forms import Registrationform ModuleNotFoundError: No module named 'templates' -
How to join two querysets from different model to create a new queryset with additional fields?
Currently on Django/MySQL setup I need to join two queries from different models into one but unlike CHAIN or UNION(), I need the final queryset's record set to expand to include data retrieved from both queries based on the common key (sales_date) as well as a SUM field. Please see below for better explanation of my question: querysetA: id sales_date store_sales 1 2020-01-15 2000.00 2 2020-01-16 1000.00 3 2020-01-17 3000.00 querysetB: id sales_date online_sales 1 2020-01-15 1500.00 2 2020-01-16 800.00 3 2020-01-17 2800.00 Joined querysetC from querysetA and B (my target result querysetC): id sales_date store_sales online_sales combine_sales 1 2020-01-15 2000.00 1500.00 3500.00 2 2020-01-16 1000.00 800.00 1800.00 3 2020-01-17 3000.00 2800.00 5800.00 My code for both querysets as below (both working and giving me the correct results): querysetA = store_shop.objects.filter( sales_date__range=(fromdate, todate)) \ .values('sales_date') \ .annotate(store_sales=Sum('sales_income')) \ .order_by('sales_date') querysetB = online_shop.objects.filter( sales_date__range=(fromdate, todate)) \ .values('sales_date') \ .annotate(online_sales=Sum('sales_income')) \ .order_by('sales_date') Both union() and itertools.chain does not give me what I want. Any help or suggestions would be greatly appreciated. -
Deserializer JSON objects containing Jason web signatures in Django. App Store Server Notifications responseBodyV2
So I have a python django rest application that I need it to be able to handle post request for App Store Server Notifications. Thing is that v2 of the App Store Server Notifications payload is in JSON Web Signature (JWS) format, signed by the App Store. Which contains fields that in turn are also in JSON Web Signature (JWS) format, signed by the App Store. I know how to handle that using python-jose procedurally but I can't figure out how to fit the whole process within Django serializers in a graceful manner with as minimal hacking as possible. The data could be something like: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub3RpZmljYXRpb25UeXBlIjoidHlwZSIsInN1YnR5cGUiOiJzdWJfVHlwZSIsIm5vdGlmaWNhdGlvblVVSUQiOiJzdHJpbmcgbm90aWZpY2F0aW9uVVVJRCIsImRhdGEiOnsiYXBwQXBwbGVJZCI6MTIzNCwiYnVuZGxlSWQiOiJhZmRzYXNkIiwiYnVuZGxlVmVyc2lvbiI6ImJ1bmRsZVZlcnNpb24iLCJlbnZpcm9ubWVudCI6ImVudmlyb25tZW50Iiwic2lnbmVkUmVuZXdhbEluZm8iOiJleUpoYkdjaU9pSklVekkxTmlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGRYUnZVbVZ1WlhkUWNtOWtkV04wU1dRaU9pSjBaWE4wSUhSdmJHVnRJaXdpWVhWMGIxSmxibVYzVTNSaGRIVnpJam94TENKbGVIQnBjbUYwYVc5dVNXNTBaVzUwSWpvMExDSm5jbUZqWlZCbGNtbHZaRVY0Y0dseVpYTkVZWFJsSWpveE5qTTJOVE0xTVRReExDSnBjMGx1UW1sc2JHbHVaMUpsZEhKNVVHVnlhVzlrSWpwMGNuVmxMQ0p2Wm1abGNrbGtaVzUwYVdacFpYSWlPaUowWlhOMElIUnZiR1Z0SWl3aWIyWm1aWEpVZVhCbElqb3hMQ0p2Y21sbmFXNWhiRlJ5WVc1ellXTjBhVzl1U1dRaU9pSjBaWE4wSUhSdmJHVnRJaXdpY0hKcFkyVkpibU55WldGelpWTjBZWFIxY3lJNk1Td2ljSEp2WkhWamRFbGtJam9pZEdWemRDQjBiMnhsYlNJc0luTnBaMjVsWkVSaGRHVWlPakUyTXpZMU16VXhOREY5LnYwWW9YQUd0MTFPeVBXUk8zV2xTZDRiSWVtcVV6Q0ZJbFdjd0ZwcEI5TmMiLCJzaWduZWRUcmFuc2FjdGlvbkluZm8iOiJleUpoYkdjaU9pSklVekkxTmlJc0luUjVjQ0k2SWtwWFZDSjkuZXlKaGNIQkJZMk52ZFc1MFZHOXJaVzRpT2lKMFpYTjBJSFJ2YkdWdElpd2lZblZ1Wkd4bFNXUWlPaUp6WkdaellYTmtaaUlzSW1WNGNHbHlaWE5FWVhSbElqb3hOak0yTlRNMU1UUXhMQ0pwYmtGd2NFOTNibVZ5YzJocGNGUjVjR1VpT2lKMFpYTjBJSFJ2YkdWdElpd2lhWE5WY0dkeVlXUmxaQ0k2ZEhKMVpTd2liMlptWlhKSlpHVnVkR2xtYVdWeUlqb2lkR1Z6ZENCMGIyeGxiU0lzSW05bVptVnlWSGx3WlNJNk1UUTFMQ0p2Y21sbmFXNWhiRkIxY21Ob1lYTmxSR0YwWlNJNk1UWXpOalV6TlRFME1Td2liM0pwWjJsdVlXeFVjbUZ1YzJGamRHbHZia2xrSWpvaWRHVnpkQ0IwYjJ4bGJTSXNJbkJ5YjJSMVkzUkpaQ0k2SW5SbGMzUWdkRzlzWlcwaUxDSndkWEpqYUdGelpVUmhkR1VpT2pFMk16WTFNelV4TkRFc0luRjFZVzUwYVhSNUlqb3hORFVzSW5KbGRtOWpZWFJwYjI1RVlYUmxJam94TmpNMk5UTTFNVFF4TENKeVpYWnZZMkYwYVc5dVVtVmhjMjl1SWpveE5EVXNJbk5wWjI1bFpFUmhkR1VpT2pFMk16WTFNelV4TkRFc0luTjFZbk5qY21sd2RHbHZia2R5YjNWd1NXUmxiblJwWm1sbGNpSTZJblJsYzNRZ2RHOXNaVzBpTENKMGNtRnVjMkZqZEdsdmJrbGtJam9pZEdWemRDQjBiMnhsYlNJc0luUjVjR1VpT2lKMFpYTjBJSFJ2YkdWdElpd2lkMlZpVDNKa1pYSk1hVzVsU1hSbGJVbGtJam9pZEdWemRDQjBiMnhsYlNKOS5lbnlkTnVwd2txOTNYQ2dfeG5yYzNXTmtNNjM4NXpITnpoa0tqa3cyb3VrIn19.OgSJ4xE3r2Tw0Q4KcwPSD4YFo21uCLDgrKOtKOomijo and then the part inbetween the dots decoded could look like b'{"notificationType":"type","subtype":"sub_Type","notificationUUID":"string notificationUUID","data":{"appAppleId":1234,"bundleId":"afdsasd","bundleVersion":"bundleVersion","environment":"environment","signedRenewalInfo":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRvUmVuZXdQcm9kdWN0SWQiOiJ0ZXN0IHRvbGVtIiwiYXV0b1JlbmV3U3RhdHVzIjoxLCJleHBpcmF0aW9uSW50ZW50Ijo0LCJncmFjZVBlcmlvZEV4cGlyZXNEYXRlIjoxNjM2NTM1MTQxLCJpc0luQmlsbGluZ1JldHJ5UGVyaW9kIjp0cnVlLCJvZmZlcklkZW50aWZpZXIiOiJ0ZXN0IHRvbGVtIiwib2ZmZXJUeXBlIjoxLCJvcmlnaW5hbFRyYW5zYWN0aW9uSWQiOiJ0ZXN0IHRvbGVtIiwicHJpY2VJbmNyZWFzZVN0YXR1cyI6MSwicHJvZHVjdElkIjoidGVzdCB0b2xlbSIsInNpZ25lZERhdGUiOjE2MzY1MzUxNDF9.v0YoXAGt11OyPWRO3WlSd4bIemqUzCFIlWcwFppB9Nc","signedTransactionInfo":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBBY2NvdW50VG9rZW4iOiJ0ZXN0IHRvbGVtIiwiYnVuZGxlSWQiOiJzZGZzYXNkZiIsImV4cGlyZXNEYXRlIjoxNjM2NTM1MTQxLCJpbkFwcE93bmVyc2hpcFR5cGUiOiJ0ZXN0IHRvbGVtIiwiaXNVcGdyYWRlZCI6dHJ1ZSwib2ZmZXJJZGVudGlmaWVyIjoidGVzdCB0b2xlbSIsIm9mZmVyVHlwZSI6MTQ1LCJvcmlnaW5hbFB1cmNoYXNlRGF0ZSI6MTYzNjUzNTE0MSwib3JpZ2luYWxUcmFuc2FjdGlvbklkIjoidGVzdCB0b2xlbSIsInByb2R1Y3RJZCI6InRlc3QgdG9sZW0iLCJwdXJjaGFzZURhdGUiOjE2MzY1MzUxNDEsInF1YW50aXR5IjoxNDUsInJldm9jYXRpb25EYXRlIjoxNjM2NTM1MTQxLCJyZXZvY2F0aW9uUmVhc29uIjoxNDUsInNpZ25lZERhdGUiOjE2MzY1MzUxNDEsInN1YnNjcmlwdGlvbkdyb3VwSWRlbnRpZmllciI6InRlc3QgdG9sZW0iLCJ0cmFuc2FjdGlvbklkIjoidGVzdCB0b2xlbSIsInR5cGUiOiJ0ZXN0IHRvbGVtIiwid2ViT3JkZXJMaW5lSXRlbUlkIjoidGVzdCB0b2xlbSJ9.enydNupwkq93XCg_xnrc3WNkM6385zHNzhkKjkw2ouk"}}' and then if the fields encoded in jws format are also decoded the same way mentioned aboce it is going to ultimately look like this: { "notificationType":"type", "subtype":"sub_Type", "notificationUUID":"string notificationUUID", "data": {"appAppleId":1234, "bundleId":"afdsasd", "bundleVersion":"bundleVersion", "environment":"environment", "signedRenewalInfo":{ "autoRenewProductId": "test tolem", "autoRenewStatus": 1, "expirationIntent" : 4, "gracePeriodExpiresDate": 1636535141, "isInBillingRetryPeriod": true, "offerIdentifier": "test tolem", "offerType": 1, "originalTransactionId": "test tolem", "priceIncreaseStatus": 1, "productId": "test tolem", "signedDate": 1636535141, }, "signedTransactionInfo":{ "appAccountToken": "test tolem", "bundleId": "sdfsasdf", "expiresDate" : 1636535141, "inAppOwnershipType": "test tolem", "isUpgraded": true, "offerIdentifier": "test tolem", … -
Django query to fetch multiple GenericRelation objects for multiple objects
I need to make quite complex query in Django to display some information from two models. There is FanGroup model, where I have few instances (let's say 5 and it's fixed) of this model. Each FanGroup model except few basic information contains GenericReleation to Fan model. For each FanGroup instance I could own few Fan instances (this is variable from 1 to many Fans assigned to each FanGroup). FanGroup model: class FanGroup(models.Model): name = models.CharField(max_length=32) default_state = models.BooleanField(default=True) fans = GenericRelation(Fan, related_query_name='fan_controller') Fan model: class Fan(models.Model): fan_inventory_id = models.CharField(max_length=16) manufacture = models.CharField(max_length=32) model = models.CharField(max_length=64) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I'd like to display in one View all the Fans belonging to FanGroup. How to combine the data to display this in single query? I could do it dirty, making simple queries for Fan model with filters to FanGroup, but this is not very dynamic solution and not very elegant. -
Django SortedManyToManyField perform reorder
I have the following two models where a Product may have many categories and a Category may have many Products associated with it: from sortedm2m.fields import SortedManyToManyField class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) is_visible = models.BooleanField(default=True) categories = SortedManyToManyField(to=Category, blank=True, related_name="product_items") number = models.CharField(max_length=150, blank=True, null=True) description = models.TextField(null=True, blank=True) related_product_items = models.ManyToManyField(to="self", blank=True) class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parent = models.ForeignKey( to="self", on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategories", ) name = models.CharField(max_length=250) is_visible = models.BooleanField(default=True) My ProductOrderingSerializer serializer: class ProductOrderingSerializer(serializers.Serializer): products = serializers.ListSerializer(child=serializers.UUIDField(), required=True) category = serializers.UUIDField(required=True) My view: class ProductViewSet(ModelViewSet): @transaction.atomic @action(methods=["put"], detail=False) def order(self, request): """ this end point receives list of ids and changes order of products per category """ serializer = ProductOrderingSerializer(data=request.data) serializer.is_valid(raise_exception=True) queryset = self.queryset.filter(id__in=serializer.validated_data["products"]) category = serializer.validated_data["category"] for index, product_id in enumerate(serializer.validated_data["products"]): # how to perform product ordering per the submitted category? pass self.action = "list" return self.list(request=request) I have been trying to find a solution for the last couple days, but nothing that would work as intended. Any help would be appreciated! -
show Model members in django admin
I need to show all users in the Model (ManyToMany relationship) like this PS: this is from Group Admin as in this Question Show group members in Django Admin but it only works for Group Model. I need it for a custom Model. -
What would be a correct route for the particular view in urls.py?(Django)
I have two classes in model. class Ebuy_Fields(models.Model): source = models.CharField(max_length=10) category = models.CharField(max_length=32) rfq_id = models.CharField(max_length=32) rfq_title = models.TextField() class Ebuy_Detail_Fields(models.Model): rfq_id_final = models.CharField(max_length=10) rfq_id_title_final = models.TextField() These are two different tables but rfq_id_final are common between them. (But they are not related by foreign key) In views.py, def ebuy_detail(request,rfq_id_final): unique_bid = get_object_or_404(Ebuy_Fields,rfq_id_final=rfq_id_final) context = {'i':unique_bid} return render(request,'rfq-display.html',context) This displays the particular view of the particular rfq_id. In urls.py, I tried with this: url(r'^(?P<rfq_id_final>[\w-]+)/$', ebuy_detail, name='ebuy_detail'), In templates when I click this line from the page of another view, <td data-label="RFQ Id"><a href = "{% url 'ebuy_detail'/{{ i.rfq_id }} }">{{ i.rfq_id }}</td> What is the correct way that if the rfq_id and rfq_final_id is same then, it will open the detail view? -
Set AWS S3 ACL per object with Django Storages
I am using django storages with the AWS_DEFAULT_ACL set to public read. However I want to be able to manually save files with default_storage.save() with private ACL. Is there a way to do this with default_storage? Something like: default_storage.save(file_name, ContentFile(content), acl='private') -
How to pass a particular value inside a Tuple that also a tuple in Python in Django?
I have this dictionary for Categories that's a tuple within a tuple however I want to isolate only the literals --> the category names from django.db import models CATEGORIES = ( ('a', 'Clothing'), ('b', 'Electronics'), ('c', 'Furniture'), ('d', 'Kitchen'), ('e', 'Miscellaneous'), ('f', 'None'), ) but in a different file that's views.py is this def show_category_listings(request, category): listings = Listing.objects.filter(category__in = category[0]) cat = dict(CATEGORIES) return render(request, 'auctions/categSpecific.html', { "listings": listings, "category": cat[category] }) and finally in the html is this <li>Category: {{ listing.category }}</li> but what i see is only letters instead of the names look in html is there a way to get only the category names? i couldn't figure out the passing of values in the views.py part. -
How to add search functionality to "list_filter"s input bar?
How to make list_filter's input text area search bar? for example as below if I write to joined_date field "10 august" and hit enter, it should filter and show all the users for corresponding date as below shown enter image description here below i attached snippet from admin.py @admin.register(User) class UserAdmin(BaseUserAdmin): template = "users_admin_template.html" list_display = [ 'first_name', 'last_name', 'surname', 'email', ] list_filter = ['first_name', 'last_name', 'surname', 'email', 'birthday','date_joined', 'country', 'city'] -
Database structure django
I have a MySQL database with three tables (three endpoints in api) but when I added JWT Django authorization it created a few more tables like customuser, tokens. Should I include those tables in my database structure diagrams? -
I want to calculate the GPA and Grade of each students regarding the each subjects. And finally calculate the Total GPA and Grade
i have tired making the models of each subject with gpa and grade. And started calculating GPA and Grade. There are 10 classes with different subjects. Can anyone suggest me the best way of calculating this. class NurseryResult(models.Model): roll_number = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=50, blank=False) academic_Year = models.CharField(default=0, blank=True, max_length=50) nepali = models.PositiveIntegerField(default=0, blank=True) nepali_gpa = models.FloatField(default=0, blank=True) nepali_grade = models.CharField(default=0, blank=True, max_length=50) english = models.PositiveIntegerField(default=0, blank=True) english_gpa = models.FloatField(default=0, blank=True) english_grade = models.CharField(max_length=50, blank=True, default=0) math = models.PositiveIntegerField(default=0, blank=True) math_grade = models.FloatField(default=0,blank=True) math_gpa = models.CharField(max_length=50, default=0, blank=True) science = models.PositiveIntegerField(default=0, blank=True) science_grade = models.FloatField(default=0, blank=True) science_gpa = models.CharField(max_length=10, blank=True, default=0) oral_nepali = models.PositiveIntegerField(default=0, blank=True) oral_math_grade = models.FloatField(default=0, blank=True) oral_math_gpa = models.CharField(max_length=50, default=0, blank=True) oral_math = models.PositiveIntegerField(default=0, blank=True) oral_math_grade = models.FloatField(default=0, blank=True) oral_math_gpa = models.CharField(max_length=50, default=0, blank=True) oral_english = models.PositiveIntegerField(default=0, blank=True) hygiene = models.PositiveIntegerField(default=0, blank=True) hygine_grade = models.FloatField(default=0, blank=True) hygine_gpa = models.CharField(max_length=50, default=0, blank=True) grade = models.CharField(max_length=10, default=0) GPA = models.FloatField(default=0) def save_nepali(self, *args, **kwargs): if self.nepali >=90: self.nepali_gpa = 4.0 self.nepali_grade = "A+" elif self.nepali >=80 : self.nepali_grade = "A" self.nepali_gpa= 3.6 elif self.nepali >= 70: self.nepali_grade = "B+" self.nepali_gpa = 3.2 elif self.nepali >= 60: self.nepali_grade = "B" self.nepali_gpa = 2.8 elif self.nepali >= 50: self.nepai_grade = "C+" … -
Converting datetime format got this issue 'str' object has no attribute 'strftime' in DRF
I have a date time value November 10, 2021 which is to be converted into Django default datetime. I tried but got this error. I have a date value which I got from list of dictionaries like this which is a datetime field. created_at = data[0]['created_at'] print(created_at) The print I got is like June 12, 2021 Now I tried this. c = created_at.strftime(('%Y-%m-%d %H:%M:%S')) print(created_at) print(c) When I print c, I got the above error. -
I want to populate / store data from csv into django admin
I want to get data from CSV and populate it to Django admin. but due to foreign key user I am not getting the desired result. def handle(request): df = pd.read_excel('testdata.xlsx') obj=Account.objects.filter(email=df.user[0]) for session_date,session_time,session_name,duration,i in zip(df.session_date,df.session_time,df.session_name,df.duration,obj): models = GuidedSession(session_date=session_date,session_time=session_time,session_name=session_name,duration=duration,user=i) # print(i) print(models # models.save() return HttpResponse(status=200) (Views.py) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60) username = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email class GuidedSession(models.Model): session_date = models.CharField(max_length=200) session_time = models.CharField(max_length=200) session_name = models.CharField(max_length=200) duration = models.IntegerField(default=20) user = models.ForeignKey(Account, on_delete=models.CASCADE) def __str__(self): s = str(self.session_name) return s (Models.py) Let me know the best way to do that. -
ArragAgg annotation wierdness. Is this a bug or a feature?
Quick problem statement. Adding an ArrayAgg (Postgres extensions) annotation is multiplying the values of other annotations, but not always. Details. Given these models: class MemDesc( models.Model): class Meta: verbose_name = "Item Description" ... lots of data fields (Char and Integer fields) class MemStockLineManager( models.Manager): def get_queryset(self): # always fetch related descriptions! return super().get_queryset().select_related('desc', 'allocated_to') class MemStockLine( models.Model): class Meta: verbose_name="Stock Line" # managers. first is default objects=MemStockLineManager() desc = models.ForeignKey( MemDesc, models.PROTECT, related_name='stock') ... data fields ... class ProductCode( models.Model): class Meta: unique_together=[('code','customer'), ('customer', 'description')] customer = models.ForeignKey( 'customers.Customer', models.CASCADE, null=True, blank=True, ) description = models.ForeignKey( MemDesc, models.CASCADE, ) code = models.CharField( max_length = 20) I don't expect MemStockLineManager is relevant but I've included it just in case. Can anybody explain these results? This as expected: >>> from django.db.models import Q,F, Sum, Count >>> from django.db.models.functions import Coalesce >>> from django.contrib.postgres.aggregates import StringAgg, ArrayAgg >>> qsx = MemDesc.objects.all().annotate( stocklines= Coalesce( Count('stock__qty'), 0), ... stocklevel= Coalesce( Sum('stock__qty'), 0)) >>> qs1 = qsx.filter(pk=140); o = list(qs1)[0]; o.stocklines 11 >>> o.stock.count() 11 Add ArrayAgg annotation, the stocklines annotation gets doubled. >>> qsx = MemDesc.objects.all().annotate( stocklines= Coalesce( Count('stock__qty'), 0), ... stocklevel= Coalesce( Sum('stock__qty'), 0) , ... partnumbers=ArrayAgg('productcode__code', distinct=True)) >>> qs1 = qsx.filter(pk=140); o = … -
Casting jsonb field's value as datetime field and then querying on it throws error
I have a model with jsonb field containing datetime value {'datetime': '2021-10-18 12:37:00.000Z'} but when I cast it using annotate(datetime=Cast('jsob__datetime', output_field=models.DateTimeField())) it throws the error 'DateTimeField' object has no attribute 'model' The model looks like this class Ticket(models.Model): jsonb = models.JsonField(default=dict) I am using Python 3.10 Django 3.2.8 Any suggestions? -
Django cached queryset.last() returns None object for not None object
My code is: @ttl_cache(maxsize=50, ttl=60 * 60) def get_query_set(): return Model.objects.all().order_by('year') def get_latest(): cached_qs = get_query_set() try: return cached_qs.last().year if len(cached_qs) > 0 else None except AttributeError: print('~~~~~~~~~~~~~~~~~') print('CHECK CIRCLECI PROBLEM') print(cached_qs) print(cached_qs.last()) print(len(cached_qs)) for aa in cached_qs: print(aa) print(type(aa)) print(dir(aa)) print(hasattr(aa, 'year')) try: print(aa.year) except Exception: print('no attr for aa') print(Model.objects.all().order_by('year')) for aaa in Model.objects.all().order_by('year'): print(aaa) print(aaa.year) print('~~~~~~~~~~~~~~~~~') raise Without try-except I getting (on get_latest()) AttributeError: 'NoneType' object has no attribute 'some_field' When I catch exception it print: ~~~~~~~~~~~~~~~~~ CHECK CIRCLECI PROBLEM <QuerySet [<Model: Model object (2)>]> None 1 Model object (2) <class 'path.models.model.Model'> ['DoesNotExist', 'Meta', 'MultipleObjectsReturned', '__class__', '__delattr__', ..., 'year'] True 2019 <QuerySet []> ~~~~~~~~~~~~~~~~~ So we can see that this problem is reproducible only at CircleCI build sometimes (I don't know how to reproduce it at local machine) cached queryset is not empty length of cached queryset is 1 queryset object is not None and has attribute year value of year is 2019 real object is already deleted at DB and does not exist (physically DB table is empty) non cached queryset is empty (because of ⑥) I guess that last() trying to re-get object from DB even if queryset is cached (because of queryset lazy behaviour?). … -
ConnectionError : Max retries exceeded with url: (Caused by ProtocolError('Connection aborted. ', OSError(0, 'Error')))
I am trying to work with the Django framework with Kerberos enabled. This is the piece of code where we had timeout added, which is now commented out. dont_wait = self.kwargs.get('dont_wait', False) kerberos_auth = '' if settings.KERBEROS_ENABLED is True: kerberos_auth=HTTPKerberosAuth(mutual_authentication=DISABLED, force_preemptive=True) if dont_wait is True: try: self.session.request( self.method, self.url, json=self.kwargs.get('data', {}), headers=self.headers, verify=settings.API_CERT_PATH, auth=kerberos_auth, #timeout=0.001 ) except exceptions.Timeout: pass else: return self.session.request( self.method, self.url, verify=settings.API_CERT_PATH, json=self.kwargs.get('data', {}), headers=self.headers, auth=kerberos_auth, ) I have also increased max_retries in this statement to 10 > requests.adapters.HTTPAdapter(max_retries=1) Still, on a few actions on the UI, I am getting below error. Traceback: File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 706. chunked=chunked, File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in _make_request 382. self._validate_conn(conn) File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in _validate_conn 1010. conn.connect() File "/usr/local/lib/python3.6/site-packages/urllib3/connection.py" in connect 421. tls_in_tls=tls_in_tls, File "/usr/local/lib/python3.6/site-packages/urllib3/util/ssl_.py" in ssl_wrap_socket 429. sock, context, tls_in_tls, server_hostname=server_hostname File "/usr/local/lib/python3.6/site-packages/urllib3/util/ssl_.py" in _ssl_wrap_socket_impl 472. return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "/usr/lib64/python3.6/ssl.py" in wrap_socket 365. _context=self, _session=session) File "/usr/lib64/python3.6/ssl.py" in init 776. self.do_handshake() File "/usr/lib64/python3.6/ssl.py" in do_handshake 1036. self._sslobj.do_handshake() File "/usr/lib64/python3.6/ssl.py" in do_handshake 648. self._sslobj.do_handshake() During handling of the above exception ([Errno 0] Error), another exception occurred: File "/usr/local/lib/python3.6/site-packages/requests/adapters.py" in send 449. timeout=timeout File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 796. **response_kw File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 796. **response_kw File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" in urlopen 796. **response_kw File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py" … -
Threads keep running in python django server
When I go to mywebiste/script, the script function runs and renders the json in the browser. list = [] def script(request): i = 0 urls = ["http://www.coden.live", "http://www.hackersvilla.xyz",] http = urllib3.PoolManager() threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urls] for thread in threads: thread.start() for thread in threads: thread.join() return JsonResponse(list, safe=False) def fetch_url(url): http = urllib3.PoolManager() r = http.request('GET', url) soup = bs4.BeautifulSoup(r.data, 'html.parser') try: content = (soup.find("meta", {"name":"keywords"})['content']) list.append(content) except: print ("No meta keywords") It is displaying the data correctly. But when I refresh the page, data is displayed 4 times and so on -
Adding a Boolean Field in django taggit's model
I am building a Simple BlogApp and I am trying to add a custom Boolean Field field in whole django-taggit's base Model named TagBase. But I didn't find any information for adding a field in whole django-taggit. I am trying to add a Boolean Field with name (inbuilt) and slug (inbuilt). You can find the base (main) model of django taggit Here (django-taggit (models.py)). I also tried to extend directly from my created app's models.py models.py class TagBase(models.Model): name = models.CharField( verbose_name=pgettext_lazy("A tag name", "name"), unique=True, max_length=100 ) slug = models.SlugField( verbose_name=pgettext_lazy("A tag slug", "slug"), unique=True, max_length=100 ) boolean = models.BooleanField(default=False) But it didn't extend, it just made a new model. What I will do with Boolean Field ? I am trying to exclude about 40 tags in a query. But there isn't any boolean so i can make a difference of them. Any help would be much Appreciated. Thank You in Advance.