Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if list of objects contain an object with a certain attribute value in django template tags
I want to check if my list of objects contain an object with a certain attribute value in django tempate tags.as we know it is represented in python like: any(x.name == "t2" for x in l) so, is there some tags to express this in template tags something like: {% if any x.atype == "Other" for x in list %} {% endif %} or something else do that? -
How do I query dynamically(?) in Django?
I'm not sure the title makes sense, so let me elaborate more. So in my Django project, each user has his own list with random integers like this : numList = [1, 3, 4, 8, 10] And I have a model names Question, which looks like this: class Question(models.Model): question_number = models.IntegerField(primary_key=True) title = models.CharField(max_length = 20, default="") # And so on Now I want to query Question objects that match the numbers in the list in my views.py. def getQuestions(request): numList = [2, 3, 4, 1, 8] # this list contains random integers every time the function is called. questionsList = [] for i in range(0, len(numList)): eachQuestion = Question.objects.filter(question_number=numList[i]) questionsList.append(eachQuestion.values()) i = i + 1 # And so on This is as far as I got. And this actually is inappropriate, because what I want is queryset, not list. How do I get queryset of questions that match the numbers in numList? Thank you very much in advance. -
Django dynamic fields view
This post answers how to dynamically return a subset of fields based on the field section in the URL. This is done by creating a dynamic serializer. This works great against a ModelViewSet, but will this affect the query to the database in any way, or will it still query all the fields, and then only the selected fields are returned to the client? If it is the later, is it possible to make it so that the query to the database is only for the specific fields if any is provided, or will I have to create a view for each query I wish to make? -
Is there any way to show dynamically rendered MathML text in django using Mathjax?
I am rendering some dynamic MathML text in django templates using jQuery and AJAX. Though non-dynamic contents are rendered properly using Mathjax library, but Mathjax is unable to convert dynamic contents. Does anyone knows anyone workaround to it. -
need examples of product variations
thank you for time what you spend to help me) Can some one give me some examples of how can I create product variations in real ecommerce web app on django framework. and after that add that wariation to the shopping cart what based on the session. Variations is not different to understand, for me. but how to add product with specific variation to the shopping cart - that's where it becomes really different for me. like example, i can create variation for some product, and add it to the cart, but when we talk about updating quantity or some another shopping cart option, that's where I stuck. need some links of real world projects. please help who can) -
AJAX in fail to send
I want to send a POST request using AJAX with jQuery function. The request is sent to my Django server when I click the button. Here is the code: $(document).ready(function(){ $('#addToCart').click(function() { var productId = $('#productId').val(); alert(1) $.ajax({ url: 'hello', type: 'post', success: function(data) { alert('success'); }, error: function(data) { alert('Got an error dude'); } }); }); }); I get the '1' alert, but after that nothing happens... I've also tried this: $.ajax({ url: 'hello', type: 'post', success: function(data) { alert('success'); }, error: function(data) { alert('Got an error dude'); } }); So not inside click or ready functions and it works. when I refresh the window I get the alert 'successs'. Spend 3 hours to find a solution, but nothing works... -
Installing virtualenv 20.0.33 on a webhost without root access
All similar questions and instructions I have found, are for versions up to 16.2.0. I tried using the instructions from 16.2.0 The file used to install, was pypa-virtualenv-YYYYY/src/virtualenv.py but version 20.0.33 does not contain the file virtualenv.py. I can't find any other newer instructions where there is no pip, no pipx, no easy_install and no root access. Is it still possible? Is there perhaps a different method? I want to use django in a virtual environment. My webhost will not install django nor do they support it but if I can manage to do so without root access, they appear OK with me doing so. -
Django saving data in model through model form and foreign key
I have a model named Doctor and a model named Appoint which have doctor as a foreign key. and I have a model form to take input for the Appoint model but not for the foreign key in it. I am able to link the Doctor model through url but I am not able to save doctor(foreign key) in Appoint model. here are the 2 models:- ``` class Doctor(models.Model): docid = models.IntegerField(null=True, default=1001) name = models.CharField(max_length=40) phone = models.IntegerField() add = models.TextField() email = models.EmailField() category = models.CharField(choices=doc_cat,max_length=20) price = models.IntegerField() def __str__(self): return self.name class Appoint(models.Model): f_name = models.CharField(max_length=12) l_name = models.CharField(max_length=12) phone1 = models.IntegerField() phone2 = models.IntegerField() add = models.CharField(max_length=100) city = models.CharField(max_length=20) state = models.CharField(max_length=30) pincode = models.IntegerField() doctor = models.ForeignKey(Doctor,null=True, on_delete=models.CASCADE) day = models.CharField(max_length=30) timeslot = models.CharField(max_length=30) symptom = models.CharField(max_length=200) email = models.EmailField() date = models.DateField(auto_now=True) def __str__(self): return self.f_name + self.l_name``` here is the view method:- ``` def takeappointment(request, docid): doctor = Doctor.objects.get(docid = docid) if request.method == 'POST': form = Appointform(request.POST) if form.is_valid(): form.save() f_name = request.POST['f_name'] l_name = request.POST['l_name'] day = request.POST['day'] timeslot = request.POST['timeslot'] email = request.POST['email'] return render(request, 'submit.html', { 'f_name' : f_name, 'l_name' : l_name, 'day' : day, 'timeslot' : … -
How to set a file that composed newly in views.py to filefield and save to upload_to path?
I need to compose a file in views.py, and set the file to filefield in a createView. Here is my codes looks like: models.py: class A(models.Model): data = models.CharField() file = models.FileField(upload_to='%Y/%m/%d/', blank=True, null=True) views.py: class ACreateView(PermissionRequiredMixin, CreateView): def form_valid(self, form): new_file_path = compose_a_new_file() ## make new file saved somewhere. form.instance.file.path = new_file_path result = super().form_valid(form) return result Here, new_file_path is the path of newly composed and saved in a folder. I just want to fill the file filefield with the newly composed file, and save it to the path defined by upload_to='%Y/%m/%d/'. (just as if I've uploaded by POST method from client) But the code above didn't save the file into '%Y/%m/%d/' folder. How can I get that? Any advice would be grateful. -
how to count in django models like in one model two foreign key field is there want to count first foreign key fields to pass on second one?
I just want to know how to count list like get all parents, for all the parents having multiple child, now need to count only child from respected parent. here is my models.py class Bins(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) bin_level = models.ForeignKey(BinLevel, on_delete=models.CASCADE, blank=True, null=True) bin_id = models.CharField(max_length=255) class Meta: db_table = 'bins' def __str__(self): """Return string representation of our models""" return str(self.id) + ' ' + str(self.bin_id) class AssignedBins(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) provincedetails = models.ForeignKey(ProvinceDetails, on_delete=models.CASCADE) municipal_council = models.ForeignKey(MunicipalCouncil, on_delete=models.CASCADE) address = models.ForeignKey(Address, on_delete=models.CASCADE) owner_name = models.CharField(max_length=255) class Meta: db_table = 'assignedbins' def __str__(self): """Return string representation of our models""" return str(self.id) + ' ' + self.owner_name class AssignBinLocations(models.Model): assignbin = models.ForeignKey(AssignedBins, related_name='assign_bin', on_delete=models.CASCADE, blank=True, null=True) bin = models.ForeignKey(Bins, on_delete=models.CASCADE,related_name='bin') latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) class Meta: db_table = 'assignedbinslocations' def __str__(self): """Return string representation of our models""" return str(self.id) here is my views.py def count(request): assignedbin = AssignedBins.objects.all() binid = [] for assignedbin_id in assignedbin: query = 'SELECT COUNT(bin_id) as bin_count from assignedbinslocations where assignbin_id ='+str(assignedbin_id.id)+';' with connection.cursor() as bincount: bincount.execute(query) list_data = dictfetchall(bincount) datas = {"list_data":list_data} return Response(datas) this is my result in postman "id": 96, "bin_location": [ { "id": 163, … -
Python Django showing empty array
I'm trying to fetch data in sql and sending it to frontend. however when i perform operations or print the array it shows null and gives no value to for loop. On the other hand when i send the array to front end it prints the data. Any help will be highly appreciated. Views.py def alldata(request): resultsdisplay=details.objects.all() for item in resultsdisplay.iterator(): allnames.append(item.username) if item.username not in names: names.append(item.username) return { "names":names, #this sends the data to front end and shows the data correctly } arr2=list() testdata=allnames arr2.append(1) arr2.append(2) arr2.append(3) time.sleep(3) print(allnames) time.sleep(3) for val in allnames: arr2.append(val) if val=="david": arr2.append(val) print(arr2) Any help will be highly appreciated -
How to change the format of HStore Field in django template?
Here I have a HStore Field in my django model. In the template it displays data in this format. {'a':'1'} But I want to display this data in the template with this format a:1 class MyModel(models.Model): properties = HStoreField() # other fields. #views.py objects = MyModel.objects.all() #template {% for obj in objects %} {{obj.properties}} # gives in the format {'a':'1'} #I want in this format. a: 1 {% endfor %} -
open cv (-215:Assertion failed) !empty() detectMultiScale
I am making a face recognition door lock. The video data from the Raspberry Pi to the camera is sent to my server. The data received from django is face_detected using the detectMultiScale function, but it is confirmed that haarcascade_frontalface_default.xml is correctly loaded as <CascadeClassifier 0000023836BAE390>, but it does not work. please help me this is my code -djnago code- -djnago code- face_detector = cv2.CascadeClassifier('haarcascades\haarcascade_frontalface_default.xml') def recvall(sock, count): buf = b'' while count: newbuf = sock.recv(count) if not newbuf: return None buf += newbuf count -= len(newbuf) return buf class streaming_pi_camera(object): def __init__(self): HOST='my ip' PORT=8485 global s s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((HOST,PORT)) s.listen(10) print('Socket Ready') global conn conn,addr=s.accept() def __del__(self): conn.close() s.close() cv2.destroyAllWindows() def get_frame(self): while True: length = recvall(conn, 16) stringData = recvall(conn, int(length)) frame = cv2.imdecode(np.fromstring(stringData, dtype=np.uint8),cv2.IMREAD_COLOR) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) print(face_detector) faces_detected = face_detector.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) for (x, y, w, h) in faces_detected: cv2.rectangle(frame, pt1=(x, y), pt2=(x + w, y + h), color=(255, 0, 0), thickness=2) ret, jpeg = cv2.imencode('.jpg', frame) return jpeg.tobytes() ` -respberry pi code- import cv2 import socket import numpy as np while True: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('my ip', 8485)) cam = cv2.VideoCapture(0) cam.set(3, 640); cam.set(4, 480); encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 100] while True: ret, frame … -
How show category title on django
My problem is that in the category pages, title, meta title and meta description are not displayed. I have shown it in the image I uploaded below. How i can fix it? Thank you modles.py class Category(models.Model): parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=70, unique=True) slug = models.SlugField(max_length=70, unique=True) description = RichTextUploadingField(blank=True, null=True) meta_title = models.CharField(max_length=120, unique=True, blank=True, null=True) meta_description = models.TextField(max_length=175, blank=True, null=True) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] views.py class PostCategoryView(generic.ListView): template_name = 'posts_category.html' paginate_by = 9 def get_queryset(self): slug = self.kwargs.get('slug') return Post.objects.filter(category__slug=slug, status=1) def get_context_data(self, **kwargs): context = super().get_context_data() context['category'] = Category.objects.all() return context category template {% extends 'shared/_MainLayout.html' %} {% load static %} {% block head %} {% block title %}**{{ category.meta_title }}**{% endblock %} {% block description %}**{{ category.meta_description }}**{% endblock %} {% endblock %} {% block content %} <div class="page-header page-header-style-1 text-center mt-50"> <div class="container"> <h2><span class="color2">**{{ category.title }}**</span></h2> <div class="breadcrumb"> <a href="/" rel="nofollow">Home</a> &nbsp; > &nbsp; <span></span><a href="/{{ category.slug }}/" rel="nofollow">**{{ category.title }}**</a> </div> </div> </div> {% endblock %} -
How to count the number of list in list items in Django templates
Here is my code: {% for category in category_list %} {% if category.age >= 18 and category.age <= 35 %} {{ category.age }} // <----- How to count this list? {% endif %} {% endfor %} category.age is a list of person from age 18 to 35. How can I count the number of person with age 18 to 35? Thanks in advance to those who can give me the answer. Godbless us all!... -
Unable to deliver static files in django
I ran the collect static script and I am still not able to deliver the static files. My static files folder - F:\Python\REALESTATE\static and inside that are all js, CSS, and IMG folders. I suspect this is not working properly - os.path.join(BASE_DIR, 'static') I have faced problems with this before also. My Setting.py files STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'REALESTATE/static') ] My html file: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %} " /> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %} " /> <!-- Custom --> <link rel="stylesheet" href="{% static 'css/style.css' %} " /> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %} " /> -
Firebase Storage file uploading 'Connection aborted.' error
I am getting an intermittent issue while uploading a file in Firebase Storage from my Django web app- 'Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None) The error page from web is below- Below is my code for uploading the file: def upload_file(name, file_obj, file_path=None, overwrite=False, retry=True): if not file_path: file_path = os.path.join(settings.MEDIA_ROOT, name) if default_storage.exists(file_path) and not overwrite: filename = default_storage.get_available_name(name) file_path = os.path.join(settings.MEDIA_ROOT, filename) default_storage.save(file_path, file_obj) return filename else: default_storage.save(file_path, file_obj) return name Here my storage setting is DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' Is there any better solution to solve the issue other than retrying the connection? Please suggest also if I am doing anything wrong here? -
How to get the difference of each qty of 2 django table?
I have here 2 different Django Models. class Stocks(models.Model): name = models.CharField(max_length=100) qty = models.FloatField() class Sold(models.Model): name = models.CharField(max_length=100) qty = models.FloatField() How to get the difference of each qty ? For example : Stocks.qty - Sold.qty How to do this? -
Downloading image files from s3 bucket from client side
I am building a website where I am uploading wallpapers on s3 bucket and I want users to be able to download those wallpapers from my website on the click of a button. Earlier I was using simple anchor tag and download attribute to download the image file but now if I click on he download button my image just opens in full size in new tab. I am not sure why this is happening and how can I Fix this. I want to be able to download the image on click not open it new tab. -
How to get increase a variable valu by jquery in django template?
At first i want to select variable form_show then i want to increase form_show variable value by jquery and return the variable value in template. How is it possible by jquery? {% extends 'base/base.html' %} {% load static %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="card-body"> <div class="card-body"> <div id="form_show" class="form-horizontal"> {{ employAcademicFormSet.management_form }} {% with form_show=1 %} {% for form in employAcademicFormSet|slice:form_show %} {% for field in form.visible_fields %} <div class="form-group row"> <label class="col-md-3 col-form-label" for="text-input"><h6>{{ field.label_tag }}</h6></label> <div class="col-md-9">{{ field }}</div> </div> {% endfor %} {% endfor %} {% endwith %} <input type="button" value="Add More" id="add_more" /> </div> </div> </div> <div class="card-footer"> <button class="btn btn-lg btn-primary" type="submit">Submit</button> </div> </form> </div> <script> $("#form_show").select(function () { var form = $("#form_show").val(); var form = 0+1; console.log(form); }); </script> {% endblock %} Please anybody help for problem... -
How to serialize annotated field in Django WITHOUT using viewsets?
I have an annotated field I am trying to include in the response to an AJAX get request. Code: backend: def ajax_get_tags(request): if request.is_ajax(): data = json.dumps( serializers.serialize("json", Tag.objects.annotate(word_count=Count('words')).order_by('-word_count'), fields=('text', 'is_game'))) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) frontend: $.getJSON("{% url 'get_all_tags' %}", function (result) { result = JSON.parse(result); }); How can I send the word count to the frontend? I found Aggregate (and other annotated) fields in Django Rest Framework serializers but I don't want to convert my endpoint to a viewset -
group by date with sum along with other data in django
I have a model named Attendance with following fields, models.py class Attendance(models.Model): project_name_id = models.ForeignKey('Project',on_delete=models.DO_NOTHING,null=True,blank=True,related_name='projects') name = models.CharField(max_length=100,null=True,blank=True) company_name = models.CharField(max_length=100,null=True,blank=True) work_type_id = models.ForeignKey('Works',on_delete=models.DO_NOTHING,null=True,blank=True) is_fullday = models.BooleanField(default=False) is_halfday = models.BooleanField(default=False) total_number = models.IntegerField(default=0) date = models.DateField(null=True,blank=True) I am trying to display the data in the following format, 05/10/2020 project_a 25 1 Carpentry 15 2 Plumbing 10 05/10/2020 project_b 8 1 Electrical 8 06/10/2020 project_a 10 1 Plumbing 10 grouping by date for each project,showing the total number of workers and showing number of workers for each work below. I can't get it to display the details for each date. This is my view, def attendanceList(request): att_objs= Attendance.objects.filter(company_name =request.session['company_name']).values('date','project_name_id__project_name').order_by('date').annotate(sum=Sum('total_number')) return render(request,'projects/attendance_list.html',{'object_list':att_objs}) How do i get all the data grouped by date and project_name with a total for each date, so that it can be displayed in the format? -
TypeError: unsupported operand type(s) for |: 'str' and 'Q'
I am having a model class ProjectPlan(Model): plan_name = models.CharField(max_length=255, blank=True) plan_manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) I need to filter a search query THis is my ORM query plan = ProjectPlan.objects.filter(models.Q(plan_name__icontains= self.context['query'])| models.Q(plan_manager__first_name__icontains= self.context['query'])) It showing an error TypeError: unsupported operand type(s) for |: 'str' and 'Q' -
Django rest framework doesn't allow a POST with multiple nested objects
I'm having an issue passing several children OrderItem, a collection, when creating an Order parent instance. Although there a one to many relationship between Order and OrderItem models, I can't pass a list of children to the parent. For some reason the parent object does not accept a list for its children, only 1 object and I don't understand why that is. Have tried many different ways to solve this, have commented on related SO questions but haven't found any solution so far. Does anyone know what I'm doing wrong or missing? Thanks for your responses! Here is an example of the request I try to make on this endpoint /api/orders/: { "bar_id": 2, "order_items":[ { "ref_id": 3 }, { "ref_id": 2 }, { "ref_id": 1 } ] } The error is as: { "order_items": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } } Here is my parent OrderModel: from django.db import models from .model_bar import * class Order(models.Model): bar_id = models.ForeignKey(Bar, null=True, on_delete=models.CASCADE, related_name='orders') Here is my child OrderItemModel: from django.db import models from .model_order import * from .model_reference import * class OrderItem(models.Model): order_id = models.ForeignKey(Order, null=True, on_delete=models.CASCADE, related_name='order_items') ref_id = models.ForeignKey(Reference, null=True, on_delete=models.CASCADE, … -
why I can't show my converted video in web site?
I made my web app using django and it works good in local server. I uploaded slowmotion video and I could download my converted video on web However, when I use AWS or pythonanywhere to release my website, I dosen's covert uploaded video. I can only show my uploaded origin video and there is nothing result. can you help me? from django.shortcuts import render, redirect from django.core.files.storage import FileSystemStorage import cv2 def upload(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['videoname'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) tujuan = context['url'][1:] modfile = tujuan + '.mp4' context['modurl'] = context['url']+'.mp4' cap = cv2.VideoCapture(tujuan) # 재생할 파일의 넓이와 높이 width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) print("재생할 파일 넓이, 높이 : %d, %d" % (width, height)) # fourcc = cv2.VideoWriter_fourcc(*'mp4v') fourcc = 0x31637661 out = cv2.VideoWriter(modfile, fourcc, 30.0, (int(height), int(width))) ret, pos_frame = cap.read() while (cap.isOpened()): ret, frame = cap.read() if ret == False: break; result = cv2.addWeighted(pos_frame, 0.5, frame, 0.5, 0) result = cv2.transpose(result) result = cv2.flip(result, 1) out.write(result) pos_frame = frame cap.release() out.release() return render(request,'index.html', context)