Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter foreign key attribute(list of) in nested Django Rest?
This is the Model, and want to implement the filter attributes are Brand, Product_type, Price(price_range). Where Brand might be more than one and price in price range(example: 2000-3000), I have tried with chain filter, objects = Tyre.objects.filter(brand__name__in=brands).filter(product_type__in=types).filter( tyre_price__price__range=(min_price, max_price)) But when any one of the attribute send empty, then the result comes empty queryset. How to implement?? Thank in advance. class Brand(models.Model): name = models.CharField(max_length=100) brand_type = models.CharField(max_length=30) class Tyre(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.DO_NOTHING) product_type = models.CharField(max_length=100) normalsectionwidth = models.CharField(max_length=100) normalaspectratio = models.CharField(max_length=100) constructiontype = models.CharField(max_length=100) rimdiamter = models.CharField(max_length=100) loadindex = models.CharField(max_length=100) speedsymbol = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.PROTECT) pattern = models.CharField(max_length=100) description = models.CharField(max_length=100) warranty_summery = models.CharField(max_length=500) left_image = models.CharField(max_length=500) name = models.CharField(max_length=100) right_image = models.CharField(max_length=500) front_image = models.CharField(max_length=500) back_image = models.CharField(max_length=500) mrp = models.CharField(max_length=100) construction_type_R = models.CharField(max_length=100) brand = models.ForeignKey(Brand,models.DO_NOTHING, related_name='brand') brand_model = models.ForeignKey(BrandModel, models.DO_NOTHING) warranty_by_year = models.CharField(max_length=100) warranty_by_km = models.CharField(max_length=100) class TyrePrices(models.Model): tyre = models.ForeignKey(Tyre, related_name='tyre_price') price = models.IntegerField() vendor = models.ForeignKey(User) discount = models.IntegerField() description = models.TextField(max_length=500) discount_price = models.IntegerField() stock = models.BooleanField(default=True, db_column='stock') -
Django static CSS from multiple application when extending base.html
I have a homepage (homepage.html) in a home app in Django. I need to extend this homepage with base.html from the root directory. I also need to include header.html (that sits in the same folder of homepage.html) along with its CSS files. The challenge here is, since the homepage extends base.html, all css stylesheets available to the homepage.html is present in the base.html. This is because, the inclusion of header.html only happens in the body and the CSS is not available in the head section. Is there any way to push the CSS files of header.html into the homepage so that the stylesheets are available in the head? Looking forward -
How to improve response speed in a website, where a picture is drawn in real time at backend, using python-django
I hope to improve response speed as much as possible, and I test the time my drawing function, which spends 2.9~3.2 seconds. Any tips to improve the speed are appreciated, from algorithm, program, website design... The during time between 'user click draw button' and 'show picture in browser' is too long, using python and django, how can I reduce the time? Thanks in advance. load 1.999396 angle2plane 3.0000000000196536e-05 getPoint 7.000000000090267e-06 getGrid 0.003222000000000058 D2MapD3 0.584085 getValue 0.032258999999999816 show 0.35327399999999987 total 2.982803 beg=time.clock() ds=loadArray(filepath, (110,110,187)) end=time.clock() print("load", str(end-beg)) ds=np.clip(ds, 0, 1) print("alpha, beta, gamma:", alpha, beta, gamma) beg=time.clock() plane=angle2plane(alpha, beta, gamma, dis) end=time.clock() print("angle2plane", str(end-beg)) beg=time.clock() A, B, C=getPoint(plane) end=time.clock() print("getPoint", str(end-beg)) beg=time.clock() grid=getGrid(width, height) end=time.clock() print("getGrid", str(end-beg)) rowgrid=len(grid) colgrid=len(grid[0]) beg=time.clock() mpmatrix=D2MapD3(A, B, C, grid) end=time.clock() beg=time.clock() values=getValue(mpmatrix, ds, width, height) end=time.clock() print("getValue", str(end-beg)) values=values.reshape(rowgrid, colgrid) beg=time.clock() plt.imshow(values) plt.savefig("test.png") end=time.clock() print("show", str(end-beg)) -
Increase date's month by interval in the model field within filter
I am getting objects like this. date_from, date_to are input variables result = Records.objects.filter(recorddate__range=(date_from, date_to)) There is another integer variable off_set. How can I use it in filter like this so the month of recorddate field is increased by off_set numbers. Like result = Records.objects.filter((recorddate+off_set)__range=(date_from, date_to)) -
Trigger to detect changes in firebase
When a child is updated or created in firebase database, I need to trigger a REST API. How to go about it? Tried using "stream" function, but in order to invoke stream everysec will have to create a cron job. I would like some trigger to be done through firebase to call API. -
Firebase Device Registration ID
How do I get the Registration ID for FCM to send push notification? I want to fetch it from my PYTHON code or from JAVASCRIPT. {'multicast_ids': [5315390988252285793], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration'}], 'topic_message_id': None} -
How to populate inlineformset for many to many related models?
This might be a noob question but I've not found solution fitting to my requirement yet, thus posting this question. I've a many-to-many relationship established using an intermediate model. User would enter InwardOrder along with its related OrderLineItem. This part is working perfectly fine. Now, I wish to add OutwardOrder in the simillar fashion. User would enter OutwardOrder by selecting InwardOrder AND the OrderLineItem should gets auto-populated based on selected InwardOrder. Then user would change quantity field only and would save. Which should update the OrderLineItem for the field user entered and tag the OutwardOrder being created. Basically, while creating OutwardOrder, I want to update OrderLineItem and associate it with the OutwardOrder. Please find below my code till now. Any help would be highly appreciated. Thanks. models.py class InwardOrder(models.Model): lot_number = models.CharField(max_length=10, blank=True, null=True) in_date = models.DateTimeField(auto_now=False, blank=True, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class OutwardOrder(models.Model): customer_out = models.ForeignKey(Customer, on_delete=models.CASCADE) out_date = models.DateTimeField(auto_now=False) inward_order = models.ForeignKey("InwardOrder", on_delete=models.CASCADE) class OrderLineItem(models.Model): inward_order = models.ForeignKey(InwardOrder, on_delete=models.CASCADE, blank=True, null=True) outwar_order = models.ForeignKey("OutwardOrder", on_delete=models.CASCADE, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) container_type = models.ForeignKey(ContainerType, on_delete=models.CASCADE) quantity_in = models.IntegerField(default=0) quantity_out = models.IntegerField(default=0) quantity_stock = models.IntegerField(default=0) forms.py InOliFormSet = inlineformset_factory( InwardOrder, OrderLineItem, fields=('inward_order','product', 'container_type', 'quantity_in',) ) OutOliFormSet = inlineformset_factory( … -
django elasticsearch giving empty records while the database has records
models.py class PostJob(models.Model): job_title = models.CharField(max_length=256) job_description = models.TextField() key_skills = models.TextField() job_type = models.IntegerField() offered_salary_range = models.CharField(max_length=256,blank=True,null=True) experience_range = models.CharField(max_length=256,blank=True,null=True) education = models.CharField(max_length=256,blank=True,null=True) industry = models.CharField(max_length=256,blank=True,null=True) application_acceptence_date = models.CharField(max_length=256,blank=True,null=True) additional_skills = models.CharField(max_length=256,blank=True,null=True) job_posted_by = models.CharField(max_length=256,blank=True,null=True) job_posters_email = models.CharField(max_length=256,blank=True,null=True) company = models.ForeignKey(access_models.EmployerRegister,on_delete=models.CASCADE,related_name='post_jobs',null=True,blank=True) def __str__(self): return self.job_title documents.py from django_elasticsearch_dsl import DocType, Index # from seeker.models import AppliedJobs from employer.models import PostJob # from access.models import SeekerRegister jobs = Index('jobs') @jobs.doc_type class AppliedJobsDocument(DocType): class Meta: model = PostJob fields = [ 'job_title', 'job_description', 'key_skills', 'job_type', 'offered_salary_range', 'experience_range', 'education', 'industry', 'application_acceptence_date', 'additional_skills', 'job_posted_by', 'job_posters_email', ] views.py from .documents import AppliedJobsDocument from django.http import JsonResponse def search_applied_jobs(request): q = request.GET.get('q') print(q) jobs = AppliedJobsDocument.search().query("match", title=q) lst=[] dict ={} for i in jobs: print(i) return JsonResponse(lst,safe=False) settings.py: ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' }, } i have added 'django_elasticsearch_dsl' in the APP also i am trying to use elastic search with django and above is my codes. i my database there is records but i am getting empty data when i am trying to print it in my console. i have installed java and elastic search is coming in port localhost:9200 also please have a look into my code. -
DIsplay image name when loading existing instance of form django
views.py : ImageFormSet = inlineformset_factory(Task,Images, form=ImageForm,min_num=0, max_num=3, validate_min=True,extra=3) formset = ImageFormSet(request.POST, request.FILES, instance=task[0]) if formset.is_valid(): formset.save() I have an image formset.I want the inline formset to display the image name if it already exists.As of now it is not showing the names of images and appears to the user as if none has been added. -
How to insert multiple values to a same field in the model
I have a model as follows class TestModel(models.Model): field1 = models.TextField() field2 = models.CharField(max_length=200, unique=True) field3 = models.CharField(max_length=200) possibleValues = models.TextField() I want to save multiple values to the field possibleValues. How can I implement such a model, and how can I save it? -
Django include template along with its css
I am trying to include a template - header.html into the main.html file. The header.html has its own css file. I have one choice- to link the css into the head of header.html and then include it. But it makes the code looks messier with many html tags in the same document. For instance, if I need to include another footer.html, again additional html tags will come to the main.html. Another option is to simply put all the styles into one main.css file and include that in the base.html. But again it makes main.css harder to edit. Is there any better solutions? Thanks -
Cannot set values on a ManyToManyField which specifies an intermediary model
How can I set values on to a ManyToManyField which specifies an intermediary model? -
How to create a CRUD REST API for all Django models with DRF?
How would one go about taking all models from all applications in django and then expose all of them under a systematic CRUD endpoint such as api/models/**** without writing DRF Views for each model individually? In other words, how does one create a generic CRUD API for all models of an application to quickly modify data in the database via REST? -
django runserver hangs when called within docker-compose.yml but not when run directly from docker-compose run
Problem Calling docker-compose up executes runserver but hangs at some point after printing the current time. Calling docker-compose run -p 8000:8000 web python manage.py runserver 0.0.0.0:8000 also execute the server, but does so succesfully and can be reached at 192.168.99.100:8000. Questions How come I can run the server directly from docker-compose in my shell but not from the .yml file? To me, the content of the .yml file and the docker-compose run line from the shell are strikingly similar. The only difference I can think of would perhaps be permissions at some level required to properly start a django server, but I don't know how to address that. Docker runs on a windows 8.1 machine. The shared folder for my virtual machine is the default c:\Users. Files My folder contain a fresh django project as well as these docker files. I've tampered with different versions of python and django but the result is the same. I've cleaned up my images and containers between attempts using docker rm $(docker ps -a -q) docker rmi $(docker images -q) docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver localhost:8000 volumes: - .:/code ports: - "8000:8000" Dockerfile FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 … -
Create pagination dynamically an html table using django
I would like to create an HTML table paginator using a view in Django. Thus, I populated my HTML table from data in a csv file using javascript, and now noticing that data in this table is very huge, I want to paginate it using Django technique. Below is my view code and the html page in which I loaded my table and would like to paginate. from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.shortcuts import render def home(request): return render(request, 'home.html', {}) {% extends "base.html" %} {% load static %} {% csrf_token %} {% block content %} <script type="text/javascript" src="https://ajax.googlespis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="{% static 'js/populate_table.js' %}"></script> <script src="{% static 'js/dataTables.bootstrap.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery.dataTables.min,js' %}"></script> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="{% static 'js/jquery.dataTables.min' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/dataTables.bootstrap.min.css' %}"> <h3 align = Center> Upload CSV file for predicting reopened pull requests</h3> <br> <p align="center"><input type="file" name="csv_file" required="True" class="form-control" id="fileUpload" /></p> <br> <p align = Center><button class="btn btn-primary" id="upload" value="Upload" onclick="Upload()"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload &raquo;</button></p> <div id="dvCSV"> </div> <script> $('table').tablesort(); </script> {% endblock content %} -
Read Ajax post data in django
I got an Ajax request using promise in my django project: var path = window.location.pathname; fetch('/getblogs/', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({'path': path}) }).then(function (response) { return response.json(); }); The request is in a js file and there is no form. I'm trying to read data in my views.py like this: @csrf_exempt def get_blogs(request): cat_id = request.POST.get('path') print("RESULT: " + str(cat_id)) But in output I get: RESULT: None Am I missing somthing in reading post data or there is something wrong with my ajax request? -
unable to create process using '/usr/bin/env/python
I HAVE BEEN TRYING TO INSTALL DJANGO PYTHON DEBUGGER THROUGH PIP BUT TO NO AVAIL. WHEN I RUN pip install django-pdb ON THE COMMAND LINE, I GET THIS: "Retrying (Retry(total=4, connect=None, redirect=None, status=None))after connection broken by 'ProxyError('Cannot connect to proxy.'..." THEN, I DOWNLOADED django-pdb file and put in my directory "C:\Users\goodnews\django-pdb.0.6.2" AND ON THE COMMAND PROMPT UNDER "C:\Users\goodnews\django-pdb.0.6.2>" I RAN setup.py install, YET I WOULD GET THIS "unable to create process using '/usr/bin/env/python". PLEASE HELP ME RESOLVE THIS. -
mypy and django models: how to detect errors on nonexistent attributes
Consider this model definition and usage: from django.db import models class User(models.Model): name: str = models.CharField(max_length=100) def do_stuff(user: User) -> None: # accessing existing field print(user.name.strip()) # accessing existing field with a wrong operation: will fail at runtime print(user.name + 1) # acessing nonexistent field: will fail at runtime print(user.name_abc.strip()) While running mypy on this, we will get an error for user.name + 1: error: Unsupported operand types for + ("str" and "int") This is fine. But we will not get an error about nonexistent field: user.name_abc. Is there a way for mypy to handle these errors? -
Django rest framework add more data when serialize many object
I would like to add an additional field for user's details. But it has to use another value outside of database fields. For more clearly like this model: class User(models.Model): id= models.AutoField(primary_key=True) last_name= models.CharField(max_length=20) first_name=models.CharField(max_length=20) role_id = models.IntegerField() serializer: class UserSerializer(serializers.ModelSerializer): display_summary = serializers.SerializerMethodField() login_user_id = serializers.IntegerField(required=False) class Meta: model = User fields = ("id","last_name","first_name", "display_summary", "login_user_id") def get_display_summary(self, obj): login_id = self.validated_data.get('login_user_id', None) login_user = User.objects.filter(pk=login_id).first() if obj.role_id==2 and login_user.role_id==1: return 1 return 0 So in my views, when getting just one user, it's all ok: @api_view(['GET']) @login_required def get_user(request, login_user, user_id): serializer = UserSerializer(User.objects.get(pk=user_id), data={'login_user_id': login_user.id}) if serializer.is_valid(): result = serializer.data return Response(result, status=status.HTTP_200_OK) #result: #{ # "id": 2, # "last_name": "V", # "first_name": "Lich", # "role_id": 2, # "display_summary": 1 #} But when I need to return a list, how can I add additional data (login_user_id)? This is not working: users = User.objects.filter(last_name__icontains='v') result_serializer = UserSerializer(users, data={'login_user_id': login_user.id}, many=True) return result_serializer.data The error occur say that it's looking for a list, not a dict for inputted param. -
django export to html page to pdf
i use django and i want to export some my html pages with tables and values from my database in django app to pdf using reportlab i try to follow this manual. working i take a pdf with Hello world but how to put in this pdf my html page of my query from django like mymodel.objects.all() ? any idea ? def write_pdf_view(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' buffer = BytesIO() p = canvas.Canvas(buffer) # Start writing the PDF here p.drawString(100, 100, 'Hello world.') # End writing p.showPage() p.save() pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
how to setup django-mongodb inside docker using djongo engine
doker-file: FROM python:3.6 WORKDIR /usr/src/jobsterapi COPY ./ ./ RUN pip install -r requirements.txt CMD ["/bin/bash"] docker-compose: version: '3.6' services: #Backend API jobsterapi: container_name: jobsterapi build: . command: python src/manage.py runserver 0.0.0.0:8000 working_dir: /usr/src/jobsterapi links: - mongodb depends_on: - mongodb ports: - "8000:8000" volumes: - ./:/usr/src/facerecognition-api mongodb: restart: always image: mongo:latest container_name: "mongodb" environment: - MONGO_INITDB_ROOT_USERNAME=${soubhagya} - MONGO_INITDB_ROOT_PASSWORD=${Thinkonce} - MONGODB_USERNAME='soubhagya' - MONGODB_PASSWORD='Thinkonce' - MONGODB_DATABASE=='jobster' volumes: - ./data/db:/var/micro-data/mongodb/data/db ports: - 27017:27017 command: mongod --smallfiles --logpath=/dev/null # --quiet django-database setting: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'jobster', 'user': 'soubhagya', 'password':'Thinkonce', 'port': 27017 } } i don't know actually how to setup django with mongodb inside docker-compose. i am trying from some blogs by this way. but it is not working. please have a look into my code. -
How to pass specific order pk to the bootstrap modal in Django?
Is there a way to pass the pk of specific let's say order pk to bootstrap model? I have tried using jquery but template tag {% url 'accept' pk=orderPK %} is causing the issue. I have tried giving it directly or with template tag but seems not working. $(document).on("click", "#accept_button", function () { let orderID = $(this).data('id'); {#url = "{"+"%"+" url 'accept' pk = " + orderID + " %"+"}";#} url = "{% url 'accept' pk =" + orderID +" %}"; #with template tag {#url = "accept/"+orderID#} #directly $(".modal-body .form").attr('action', url ); Error: TemplateSyntaxError at /dashboard/warehouse/response/ Could not parse the remainder: '=" + orderID +"' from '=" + orderID +"' -
Cannot find a good tutorial for RDFLib or RDFLib-SQLAlchemy?
I am developing a project for searching irrigation data. For that I am using Django and RDFLib. But I cannot find any good tutorial anywhere on the web. -
deployment Django project on CPanel
I have a ready project written in Python/Django. I am going to run it via CPanel and I watched some videos about it. But in videos they showed how to set up a Python project on CPanel not how to put a ready project. Anyone know how to deploy it? -
Missing field in database but exist in Django's model
Prevoiusly my model consist of three records id (primary key), router_id, as_num and neighbor_id then I'm trying to alter 'id' field in database by changing a field name to from 'id' to 'auto_id'. Here's my model class dataFromFile(models.Model): auto_id = models.AutoField(primary_key=True, default=0) router_ip = models.CharField(max_length=20) as_num = models.IntegerField(default=0) neighbor_ip = models.CharField(max_length=20) then using command python manage.py makemigrations peersite gave me a message "No changes detected in app 'peersite'" then using python manage.py sqlmigrate peersite 0001 seems fine with no error. But with python manage.py migrate peersite gave _mysql.connection.query(self, query) django.db.utils.OperationalError: (1091, "Can't DROP 'id'; check that column/key exists") I've checked in table dataFromFile in the database, also no 'id' field. Any solution here ? Thank you in advance