Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django App - Deployment on host (Beginners guide)
I have finished my first simple django app - online store. And now I am planning to deploy it on some free host. Goal is simple - just to have link which anyone can access in order to show the app somewhere else then on local computer. Can you recommend any beginner friendly video/guide with step-by-step explenation how to do it? -
How do I re-run npm build in React and Django?
So I'm learning React and Django, and executed npm run build to run the React App in my Django server (port 8000). Then I turned the React app off(ctrl+C), and now I'm trying to run it again. So I thought I should execute npm run build again, but it didn't work. I have the Django server running, but I have no idea how to start the React app. I know this may sound unclear, but this is the best I can explain as a beginner. How do I turn the React app back on? -
No live upstream while connecting to upstream jwilder/ngnix-proxy
The documentation is not clear to me, as well as this is my first deployment I keep getting error as 502 beacause of no live upstream. This is the code. docker.staging.yml version: '3.8' networks: public_network: name: public_network driver: bridge services: web: build: context: . dockerfile: Dockerfile.prod command: gunicorn djangotango.wsgi:application --bind 0.0.0.0:8000 volumes: # - .:/home/app/web/ - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.staging db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.staging.db depends_on: - web pgadmin: image: dpage/pgadmin4 env_file: - ./.env.staging.db ports: - "8080:80" volumes: - pgadmin-data:/var/lib/pgadmin depends_on: - db links: - "db:pgsql-server" environment: - PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org - PGADMIN_DEFAULT_PASSWORD=root - PGADMIN_LISTEN_PORT=80 nginx-proxy: build: ./nginx restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - web networks: - public_network nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy networks: - public_network volumes: postgres_data: pgadmin-data: static_volume: media_volume: certs: html: vhost: .env.staging.db VIRTUAL_HOST=djangotango.meghaggarwal.com VIRTUAL_PORT=8000 LETSENCRYPT_HOST=djangotango.meghaggarwal.com ngnix Docekrfile FROM jwilder/nginx-proxy COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf ngnix->vhost.d->default upstream djangotango { server web:8000; } server { listen 80; listen 443; server_name djangotango.meghaggarwal.com location / { proxy_pass http://djangotango; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; … -
How do I get data from a form while the user is typing in his data? Django/Python
I have a problem I am currently working on. Really new to django and python. What I am trying to do is I have a form where the user can rent a parking lots for a certain period of time. I want to be able to dynamically calculate the value of the price based on the time the user selects and show this to the user. Meaning that price x time selected will generate a price that the user should be able to see. I do have the view ready and started with a function to calculate the price, but I got stuck really fast since I can't come up with how to get the user input data before the form, where the data is entered, is submited. Below you see the view i wrote to this: def list_parking_lots(request): """ View for all parking lots :param request: request from user :return: rendered parking_mgmt/list_parking_lots.html """ parking_lots = ParkingLot.objects.all() form = ReservationForm() if request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your reservation was successfully registered.') form = ReservationForm() return render(request, 'parking_mgmt/list_parking_lots.html', {'parking_lots': parking_lots, 'form': form}) Any help is appreciated. -
Check if a parameter exists in Django URL
I am trying to get a URL if it exists in the URL but keep getting the following error: django.utils.datastructures.MultiValueDictKeyError: 'sc' The case is that the urls can be sometimes like the following: /allot-graph/ and sometimes: /allot-graph/?sc='foo' and in my function I am doing this: class AllotmentbyMonth(APIView): def get(self, request): q = request.GET['sc'] if q: print("q", q) dataset = some query else: dataset = some query -
Django Multiple requests in One Time
Now I Am Work On 'Django Multiple Requests In One Time', But When I Send the First Request And At The Time I Send the Second Request So I Get The Result of The Second Request, First Request is Closed automatically, So How I Implement Multiple Requests In One Time, Please Suggest To Me. Note:- I Work In LocalHost -
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.