Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send file to a different server
I have an upload url in my backend and i want to upload a file in another server. My API view: class AssessmentFileUpload(APIView): parser_classes = (MultiPartParser, ) def post(self, request, format=None): tenant = request.user.tenant.id response = AssessmentFileUploadHelper(tenant).upload_file(request) response_text = json.loads(response.text) print(response_text) if response.status_code == status.HTTP_201_CREATED: return Response({"message": "success", "id": response_text.get('id')}, status=status.HTTP_201_CREATED) return Response({"message": "failed"}, status=status.HTTP_400_BAD_REQUEST) My class which sends request data to the other serve's url: class AssessmentFileUploadHelper: def __init__(self, tenant_id): self.tenant_id = tenant_id def upload_file(self, file): url = settings.ASSESSMENT_CONNECTION_SETTINGS["api_endpoint"] + "tenant/" + \ str(self.tenant_id) + "/fileupload/" return RequestSender().send_request(url, file) Now, the errors im getting is InMemoryUploadedFile is not json serilizaable . How to send request.FILES to that server ? -
Django Sitemap Problem Http Error 500 on Production
I'm using django sitemap to generate my sitemap. In local it works normally, I can visit 127.0.0.1:8000/sitemap.xml and see the data. But in production, I got http error 500 (site matching query not exist). I've been following solutions on the internet, and one of those is from this link https://dev.to/radualexandrub/how-to-add-sitemap-xml-to-your-django-blog-and-make-it-work-on-heroku-4o11 , but still not solving the error. Please kindly help. Thanks -
How to query all records from a model matching two or more values in Django Model using SqlLite
I have this query inside one of my views.py My query needs to search for football matches in all the leagues specified in my query value.In addition I would like to get all upcoming matches by selecting all matches with kickoff_date say 5 days from now topgames =Predictions.objects.filter(league='Epl' or 'Bundesliga' or 'Liga BBVA' or 'The Championship',kickoff_date= // I want to fiter the kickoff_date based on a time range ie. (5 days from now) // ) -
Could not resolve URL for hyperlinked relationship using view name "api:user-detail" in Django Rest Framework
I saw many similar questions and I have followed this question Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail" but look like nothing works. Inside the UserViewSet i'm using get_queryset instead in queryset. In my UserViewSet I want to list only current user objects. # app/serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): passwordStyle = {'input_type': 'password'} password = serializers.CharField(write_only=True, required=True, style=passwordStyle) url = serializers.HyperlinkedIdentityField(view_name="api:user-detail") class Meta: model = User fields = ['url', 'id', 'username', 'password'] def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(UserSerializer, self).create(validated_data) # app/views.py class UserViewSet(viewsets.ModelViewSet): def get_queryset(self, *args, **kwargs): user_id = self.request.user.id print(user_id) return User.objects.all().filter(id=user_id) # want to list only current user objects serializer_class = serializers.UserSerializer permission_classes_by_action = { 'create': [permissions.AllowAny], 'list': [permissions.IsAuthenticated], 'retrieve': [app_permissions.OwnProfilePermission], 'update': [app_permissions.OwnProfilePermission], 'partial_update': [app_permissions.OwnProfilePermission], 'destroy': [permissions.IsAdminUser] } def create(self, request, *args, **kwargs): return super(UserViewSet, self).create(request, *args, **kwargs) def list(self, request, *args, **kwargs): return super(UserViewSet, self).list(request, *args, **kwargs) <- problem on this line def retrieve(self, request, *args, **kwargs): return super(UserViewSet, self).retrieve(request, *args, **kwargs) def update(self, request, *args, **kwargs): return super(UserViewSet, self).update(request, *args, **kwargs) def partial_update(self, request, *args, **kwargs): return super(UserViewSet, self).partial_update(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): return super(UserViewSet, self).destroy(request, *args, **kwargs) def get_permissions(self): try: # return permission_classes depending … -
Django dynamic Search View based on filled GET request keys
please how is possible in Django to reach a view, which will be filtering based on filled keys from GET request? I am using only one search view, but two forms: I am taking these requests: q = request.GET.get('q') # this is for VIN and LOT number (two columns in Model/DB) make = request.GET.get('make') model = request.GET.get('model') year_from = request.GET.get('year_from') year_to = request.GET.get('year_from') There are no required fields/requests, so it should work dynamically. If the user fills "q" - it will filter out by VIN or LOT number. If the user will fill Make and Year, it will filter out by make and to year... How is possible to do this, some better way, than if , elif, elif, elif, ... Is there any proper way, please? This is my solution, but I really dont like it, it is not professional and I don't know, how to find a better solution def is_valid_queryparam(param): return param != '' and param is not None def search_filer(request): qs = Vehicle.objects.all() # VIN and Lot number q = request.GET.get('q') make = request.GET.get('make') model = request.GET.get('model') year_from = request.GET.get('year_from') year_to = request.GET.get('year_from') if is_valid_queryparam(q): qs = qs.filter(Q(vin__icontains=q) | Q(lot_number__icontains=q)) elif is_valid_queryparam(make): qs = qs.filter(make__name__exact=make) elif … -
Unable to figure out what's missing to run my Django Project successfully
Last year, I created a Django project on real estate business. Few days back, I cleaned up my PC & I believe I removed something useful because of which I'm unable to run it on my localhost now. It was working fine before. The major tools that I used in the project include Django, PostgreSql, pgAdmin4, Bulma. As I'm trying to run it via VSCode, it's showing the following traceback. Please help me find out what's exactly missing and how can I get back the proper working flow. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was … -
What is the reason for the error ' PermissionError: [Errno 13] Permission denied ' when running the django server
When I try to run the Django server, the server runs properly, but I also get the following error and my developing website does not load properly. What could be the problem? File "C:\Users\UserName\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 183, in finish_response for data in self.result: File "C:\Users\UserName\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\util.py", line 37, in __next__ data = self.filelike.read(self.blksize) PermissionError: [Errno 13] Permission denied -
Field 'id' expected a number but got 'ANPKUR0724' while Importing Data in Django
I have two models, related through a Foreign Key, when im uploading the Model having Foreign key , the id value which is auto created is taking value of the Field which is the foreign key. What could be the possible reason?. class Station(models.Model): BS_ID = models.TextField(max_length=20,unique=True) BS_Name = models.CharField(max_length=20) City = models.CharField(max_length=20,null=True) State = models.CharField(max_length=20,null=True) City_Tier = models.CharField(max_length=10,null=True) Lat = models.DecimalField(max_digits=10,decimal_places=5,null=True,blank=True) Long = models.DecimalField(max_digits=10,decimal_places=5,null=True,blank=True) class CustomerLVPN(models.Model): Customer_Name = models.CharField(max_length=200) Order_Type = models.CharField(max_length=200,null=True) Feasibility_ID = models.IntegerField(null=True) Circuit_ID = models.CharField(max_length=250,null=True,blank=True) Req_BW = models.DecimalField(max_digits=6,decimal_places=3,null=True,blank=True) City = models.CharField(max_length=200,null=True) State = models.CharField(max_length=200,null=True) Region =models.CharField(max_length=200,null=True) L2_Lat = models.DecimalField(max_digits=6,decimal_places=3,null=True,blank=True) L2_Long = models.DecimalField(max_digits=6,decimal_places=3,null=True,blank=True) BS_ID = models.ForeignKey(Station,to_field='BS_ID',related_name='ConfirmedCustomer',on_delete=models.SET_NULL,null=True) So when im Uploading data for CustomerLVPN model im getting the following error - "BS_ID Field 'id' expected a number but got 'ANPKUR0724'." -
Single user Single Device Login using Django rest framework
I wanted to build a login system using Django Rest Framework so that user can only login in into his account through a single Device. Whenever he tried to login from a different device he automatically logged out of the previous device.What should i do for doing this? -
django.db.utils.ProgrammingError: permission denied to create extension "btree_gin" when migrate in django
I'm trying to migrate my Django project, and it creates a new database. The database has btree_gin extensions. However, when I run the command, it gives me the following error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, topup, vendor Running migrations: Applying myapp.0001_initial...Traceback (most recent call last): File "/home/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InsufficientPrivilege: permission denied to create extension "btree_gin" HINT: Must be superuser to create this extension. -
Choice Field with Radio button not appearing on the admin panel
This is my passsenger model. When I go to my default django model, I can see every fields but not the choice field. I want the option to select the gender of the patient. ALso, I want this in my form. But, there is no field name Gender in my admin panel in the first place. What is the issue?? class Passenger(models.Model): # book_id = models.OneToOneField(Booking, # on_delete = models.CASCADE, primary_key = True) First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateField(blank=False) Contact_Number = models.CharField(max_length=200, unique=True) Email = models.EmailField(max_length=200, unique=True) Customer_id = models.CharField(max_length=50) CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(label='Gender', widget= forms.RadioSelect(choices=CHOICES)) -
value error given username must be set on django python project
I'm trying register a user in my project, but when I try to do it I get next error: ValueError: The given username must be set ''' #View.py def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] first_name = request.POST['fname'] last_name = request.POST['lname'] user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user.save() print('user created') return redirect("register") else: return render(request,'register.html') ''' -
Django not null constraint failed altough positive is set
I am doing a pet project to learn django. I am coding a workout journal. When going through the admin to add a workout I input what seems reasonable data but then a NOT NULL constraint failed: workoutJournal_workout.reps error appears. Looking at the error log, it seems the data are correctly read : but I still get the above mentionned error. Below is the extract of my models.py : from django.db import models from django.contrib import admin from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.core.validators import RegexValidator class Exercise(models.Model): name = models.CharField(max_length=120, default="") def __repr__(self): return "self.name" def __str__(self): return self.name class planesOfMovement(models.TextChoices): SAGITTAL = "SA", _("Sagittal") FRONTAL = "FR", _("Frontal") TRANSVERSAL = "TR", _("Transversal") planesOfMovement = models.CharField( max_length=2, choices=planesOfMovement.choices, default=planesOfMovement.FRONTAL, ) class typeOfMovement(models.TextChoices): PUSH = "PS", _("Push") PULL = "PL", _("Pull") CARRY = "CA", _("Carry") LOAD = "LO", _("Load") typeOfMovement = models.CharField( max_length=2, choices=typeOfMovement.choices, default=typeOfMovement.LOAD, ) class Workout(models.Model): date = models.DateField(default=timezone.now) exercises = models.ManyToManyField( Exercise, through="WorkoutExercise", related_name="workout_exercises" ) def __str__(self): # __unicode__ on Python 2 return self.name class WorkoutExercise(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.DO_NOTHING) workout = models.ForeignKey(Workout, on_delete=models.PROTECT) sets = models.PositiveIntegerField() reps = models.PositiveIntegerField() tempo = models.CharField( max_length=11, validators=[ RegexValidator( r"[0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}", message="Please format your tempo as … -
Sweet Alert is not working inside ajax calls in django
Sweet Alert - https://sweetalert.js.org/guides/ I have imported Sweet Alert using CDN inside my base html file: <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> I have tried to use Sweet Alert inside ajax calls in the following way: $.ajax({ type:'POST', url: 'deliveryupdate/'+barcode2+'/', dataType: 'json', data:{ barcode: barcode2, owner: owner2, mobile: mobile2, address: address2, atype: atype2, status: "Gecia Authority Approved", statusdate: today, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(){ console.log("success log"); swal("Success!","Asset request has been approved","success"); }, error: function(){ console.log('error', arguments) swal("Error!","Some error occurred","error"); } }); This is not working, even though there are successful changes in the database, the error function is executing instead of success function, and the error sweet alert flashes for a mini-second and vanishes. The console shows error log. But if I change sweet alert to normal browser alert, it works perfectly.( but that too only in Chrome, not in firefox ) Its working perfectly when I replace swal() with alert(). (only in Chrome though) I don't want the normal browser alert, I need a good looking alert like Sweet Alert. In my other templates where there are no ajax calls and simple alerts, sweet alert is working fine with no problems. Please Help. -
Django: many to many intersec not filtering. Had problem
models.py I have to filter Consumer_order through Newspaper as m2m but intersect not filter? class Newspaper (models.Model): newspaper = models.CharField(max_length=50) language = models.CharField(max_length=50, choices=Language) wh_price = models.DecimalField(max_digits=6,decimal_places=2) sa_price = models.DecimalField(max_digits=6,decimal_places=2) description = models.CharField(max_length=50) company = models.CharField(max_length=50) publication = models.CharField(max_length=50, choices=Publication) def __str__(self): return self.newspaper class Consumer_order(models.Model): #name = models.ForeignKey(Consumer, on_delete=models.CASCADE) ac_no = models.CharField(max_length=32) newspaper = models.ManyToManyField(Newspaper,related_name="Consumer_ac_no") added_date = models.DateField(max_length=32,auto_now_add=True) Actually i did filter Consumer_order.objects.filter(newspaper__publication = 'Weekdays').values() Answer >> {'id':1,'ac_no':'2000','added_date':datetime.date(2020,9,13)} Here intersect not filter; if i invoke intersec like this Consumer_order.newspaper.all() Answer >> sunnews,daynews Actually i excepert have to filter intersec newspaper also. guy plz me i stuck 2month about this .... -
Converting numpy image to PIL image giving strange result
Actually, I need to save PIL image to django that's why i am converting numpy image to pillow image but it's giving me the strange image. from cv2 import cv2 import numpy as np import urllib.request from PIL import Image url = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a6/Deepika_Padukone_at_Tamasha_event.jpg/220px-Deepika_Padukone_at_Tamasha_event.jpg" resp = urllib.request.urlopen(url) img77 = np.asarray(bytearray(resp.read()), dtype="uint8") img77 = cv2.imdecode(img77, cv2.IMREAD_COLOR) ''' join image ''' im_h = cv2.hconcat([img77, img77]) ''' resize image ''' print('Original Dimensions : ',im_h.shape) width = 1108 #554 #1108 height = 584 #292 #584 dim = (width, height) resized = cv2.resize(im_h, dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ',resized.shape) ''' put similarity level ''' img1 = resized img2 = cv2.imread('percentage_images\\15.png') # it's percentage image(.png) rows,cols,channels = img2.shape roi = img1[0:rows, 0:cols ] img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv) img2_fg = cv2.bitwise_and(img2,img2,mask = mask) dst = cv2.add(img1_bg,img2_fg) img1[0:rows, 0:cols ] = dst nadu = Image.fromarray(img1,"RGB") print(nadu) nadu.save("what.jpg") # Image.fromarray(img1).convert("RGB").save("what2.jpg") cv2.imshow('res',img1) cv2.waitKey(0) cv2.destroyAllWindows() # cv2.imwrite('full_edit.jpg', img1) Image convert from this -> real image to this-> converted image I am new to Pillow so any help will be appreciated. Thanks Sir/Mam. -
Why is div inside of the other div?
I have the following django template code. The main-card-faq div is clearly not in the main-card div however it keeps getting rendered inside of the main-card div. Any idea what could be going on? {% extends 'base.html' %} {% block content %} <div class="main-card"> {% if heading_info %} {% for heading in heading_info %} {% include 'partials/_heading.html' %} {% endfor %} {% endif %} {% if welcome_info %} {% for welcome in welcome_info%} {% include 'partials/_welcome.html' %} {% endfor %} {% endif %} {% comment %} {% if skills_info %} {% for skill in skills_info%} {% include 'partials/_skills.html' %} {% endfor %} {% endif %} {% endcomment %} </div> <div class="main-card-faq"> {% include 'partials/_faq.html' %} </div> test {% endblock %} -
Django model returns None in AppConfig
I am trying to fetch values from mysql database using django model inside an appconfig subclass but I keep getting None. class myappConfig(AppConfig): name = 'myapp' def ready(self): from .models import myModel mydata = myModel.objects.values('A') Even though there is data in the mysql table corresponding to myModel, the value in mydata is None. What could be the reason for this ? -
Django User inheritance
I am building a food ordering website with Django. I want my users to register an account on my site, and they should sign in to actually order. I want to use the User class built in with Django, but that doesn't include necessary fields like address, confirmation ID, and phone number. If I build a custom User model, that doesn't have many good helper functions which I can use like auth.authenticate. I searched this topic, and I found that I could use AbstractUser. But when I inherited my CustomUser class from AbstractUser, some strange things began to happen. After some more research, I found out that changing the User model after applying my built-in migrations give some errors as there are some relationships or something. I deleted my database and created a new one. Now, I am extending my CustomUser class from the built-in User class. This works fine, only you can't do auth.authenticate checking with the, confirmation ID for instance. Also, it seems to create two models every time I create a new CustomUser, the other on in the Users under the auth tab. Can you tell me any good way to connect the User model with a … -
Change URL and content without refreshing django
I am fetching a json response from my django response by this url /inbox/<str:username> to get a json response of all the messages in the conversation with that user. The problem starts with the inbox page which holds the threads and chatbox on the same page like instagram which looks like this but as it can be seen that I want the url to be like with the username. Let's say when I click on thread with dummy I want the url to be like "inbox/dummy" but in this my url is "/inbox" which will not let me initiate the socket for messaging, my views.py that renders this inbox template is views for inbox thread_objs= Thread.objects.by_user(user=request.user) l=len(thread_objs) chat_objs=[] for i in range(l): chat_objs.append(list(thread_objs[i].chatmessage_set.all()).pop()) chat_objs_serialized=[] for i in range(l): chat_objs_serialized.append(json.dumps(ChatMessageSerializer(chat_objs[i]).data)) for i in range(l): print(chat_objs_serialized[i]) thread_objs_list=[] for i in range(l): thread_objs_list.append(json.dumps(ThreadSerializer(thread_objs[i]).data)) return render(request,'uno_startup/inbox.html',context={"Threads":thread_objs_list,"Messages":chat_objs_serialized}) now when I click a thread it's content should load on the right side of screen as with the javascript of inbox.html that is this page in this image. javascript of inbox <body> <div class='container'> <div class='row'> <div class="col-md-4" id ="Threadholder"> <ul id ="Threadbox"> {% for object in threads %} <li><a href=" ">{% if user != object.first %}{{ … -
how to save migration for dependency in django in git repo
According to the django documentation, I should only be running the makemigrations command on my local computer, and then when it comes time to production, I should be saving the migrations to the repo and then just running migrate with the migrations already made. This makes sense to me but I am unsure how to do this for the migrations that are created for any pip module that I use for the django site? in one of the migrations that I would save to the repo, there is a dependency on one of the migrations for a pip module but I have no clue how to save that migration to the repo since the migration exists under the site-packages folder and I get the feeling that I am not supposed to be manually moving migrations from that folder to my repo and placing it under a migrations folder for one of the apps that exists for my website's django? -
how to add a search field in graghql/django
I am working on this project: https://github.com/mirumee/saleor I added a column to the product model by doing: account_user = models.ForeignKey( Account_User, related_name="products", on_delete= settings.AUTH_USER_MODEL, ) However, after I run "npm run build-schema" and then type query { products(first: 10) { edges { cursor node { id name description slug account_user_id } } } Graghql says ""message": "Cannot query field "account_user_id" on type "Product".",". Do I miss any step? Do I need to modify the query to add this field? Thanks -
Django server crashes once deployed
The server builds successfully. Once Its built, and I go to view it, i gives me an application error. Still new to deploying via heroku and django, so if this is obvious please be helpful! It keeps saying module not found with 'locallibrary', where I do not have a module named local library. Here is the log 2020-09-29T02:20:16.043818+00:00 app[web.1]: worker.init_process() 2020-09-29T02:20:16.043818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-09-29T02:20:16.043818+00:00 app[web.1]: self.load_wsgi() 2020-09-29T02:20:16.043819+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-09-29T02:20:16.043822+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-09-29T02:20:16.043823+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-09-29T02:20:16.043823+00:00 app[web.1]: self.callable = self.load() 2020-09-29T02:20:16.043824+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-09-29T02:20:16.043824+00:00 app[web.1]: return self.load_wsgiapp() 2020-09-29T02:20:16.043824+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-09-29T02:20:16.043825+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-09-29T02:20:16.043825+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-09-29T02:20:16.043826+00:00 app[web.1]: mod = importlib.import_module(module) 2020-09-29T02:20:16.043826+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-09-29T02:20:16.043826+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-09-29T02:20:16.043827+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-09-29T02:20:16.043827+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-09-29T02:20:16.043828+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked 2020-09-29T02:20:16.043828+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-09-29T02:20:16.043828+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-09-29T02:20:16.043829+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, … -
Django dynamic url path from Pandas dataframe
I'm new to Django with some fluency in Python, primarily Pandas. I'm trying to build dynamic paths for my app, such that a user pressing a button will reference my pandas dataframe, either by index or some primary key, in order to have a unique page for each row in my dataset. More specifically I'm generating a random number to select a random row from my dataframe. I understand and have read the documentation for Django's URL dispatcher but I'm only aware of setting custom paths that can be referenced in the html by the user typing in their path and not necessarily an automated version of that. Essentially what I'm trying to accomplish is to achieve a similar result to https://www.imdb.com/title/tt0111161/ with "/title/" as my app name and "/tt0111161/" as the custom path from my primary key/index/random number of my dataframe row. I've tried various versions of this method. The views.py looks like this: def all(request, id): random_number = random.randint(0,100) row = df.iloc[random_number] id = random_number return render(request, "play/all.html", { "title": row['title'], "year": row['year'], }) The urls.py looks like this: urlpatterns = [ path("all/<int:id>/", views.all, name="all"), ] I just can't figure out how to make this functional. Is it … -
Django ORM queryset to table with one field as index, using a json response
I have a Django ORM table called Measurements as below: | pk | Length | Width | Height | Weight | Date | |----|--------|-------|--------|--------|------------| | 1 | 131 | 23 | 52 | 126 | 2019-12-01 | | 2 | 136 | 22 | 64 | 125 | 2019-12-02 | | 3 | 124 | 25 | 59 | 130 | 2019-12-03 | As can be observed, Length, Width, Height, Weight & Date are all fields. I want to send a json response such that it can be used to render a table like below: +-------------+------------+------------+------------+ | Measurement | 2019-12-01 | 2019-12-02 | 2019-12-03 | +-------------+------------+------------+------------+ | Length | 131 | 136 | 124 | +-------------+------------+------------+------------+ | Width | 23 | 22 | 25 | +-------------+------------+------------+------------+ | Height | 52 | 64 | 59 | +-------------+------------+------------+------------+ | Weight | 126 | 125 | 130 | +-------------+------------+------------+------------+ To do this I will have to return a list of 4 dictionaries where each dictionary in the list will have the following keys: Measurement, 2019-12-01, 2019-12-02, 2019-12-03. Like so: >>> dicts = [ ... { "Measurement": "Length", "2019-12-01": 131, "2019-12-02": 136,"2019-12-03": 124 }, ... { "Measurement": "Width", "2019-12-01": 23, "2019-12-02": 22,"2019-12-03": 25 }, …