Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can we custom whole Django Admin site is it possible?
here I have superuser(admin) which has a button and after clicking on it it should show another database table details in admin after clicking on button it should show all data of table -
Having a bootstrap carousel for Wagtail problem
I have been testing my code out and come across a small problem. My indicators at the bottom allow for navigation but to get to the final image in the carousel I need to click on the second last indicator? I cant see the bug :(. All the others work fine. <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ul class="carousel-indicators"> {% for item in page.blogpage_images.all %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ forloop.counter }}" class="{% if forloop.counter == 1 %}active{% endif %}"></li> {% endfor %} </ul> <div class="carousel-inner"> {% for item in page.blogpage_images.all %} {% image item.image fill-900x400 as img %} <div class="carousel-item {% if forloop.counter == 1 %}active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" alt="{{ img.alt }}"> </div> {% endfor %} </div> </div> -
How to setup Django Channel with uWSGI
My Django application is set up with uWSGI, Nginx. Everything is fine. Now I want to set up with Django Channel. The server is running good in a localhost environment, with command python manage.py runserver. But when I deploy to a server, the WebSocket URL is not found. I think I need to config the uWSGI and Nginx config. But I don't know how to do it? Does everyone have any idea? -
how to fix error in django addition url path not find not link to new code
My url path finder doeds not find result.html page when i click on submit button it will not find that result.html page . it can not find the second url path.Iam trying to add two numbers in Django a basic django Programmge in first it will open the home.html page then on click submit it will not open the result.html page on which the result is displaed i have tried to import pattrens but it will show errors pattrens can not be imported somethig like i have also tried to direct the page from This is my url.py file from django.conf.urls import include, url from django.contrib import admin from . import views admin.autodiscover() urlpatterns = [ url('', views.home,name='home'), url(r'^add/', views.add, name ='add'), ] ##this is my home.html file {% extends 'base.html' %} {% block content %} <body> <h1> Hello {{name}} !!!!!!! </h1> <form action="add"> Enter First Number : <input type="text" name ="first"> Enter Second Number : <input type="text" name ="second"> <input type ="submit"> </form> </body> ## this is my view.py file from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request,'home.html',{'name': 'Harsh'}) def add(request): val1= int(request.GET['first']) val2= int(request.GET['second']) res … -
I want to extract image cordinates from pdf in python. i am not able find any solution for python
I tried using the third party libraries but not the same thing i want. i just want the coordinates of image not the image itself. i have found some solution for text coordinate extraction using pdfminer. -
Deploy django project and frontend in apache
I'm using django==1.11 apache 2.4 django project /var/www/myproject and frontend code /var/www/html/frontend directories. I want to deploy on apache server where i have modified 000-default.conf file as <VirtualHost *:80> ServerName www.mysite.in ServerAlias mysite.in ServerAdmin myemail@abc.com DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias / /var/www/html/frontend/ <Directory /var/www/html/frontend> Require all granted </Directory> <Directory /var/www/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.in python-path=/var/www/myproject python-home=/usr/local/lib/python3.5/dist-packages WSGIProcessGroup mysite.in WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py </VirtualHost> In this case i'm not able to hit to my django rest apis. If i use <VirtualHost *:80> ServerName www.mysite.in ServerAlias mysite.in ServerAdmin myemail@abc.com DocumentRoot /var/www/ ErrorLog ${APACHE_LOG_DIR}/mysite_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /var/www/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite.in python-path=/var/www/myproject python-home=/usr/local/lib/python3.5/dist-packages WSGIProcessGroup mysite.in WSGIScriptAlias / /var/www/myproject/myproject/wsgi.py </VirtualHost> then i'm able to hit my django rest apis. Here, alias are conflicting. I'm not using my static files in my django project as i have all static files are not in myproject. How to deploy django rest apis and backend code with different directories on apache server? Thanks. -
500 apache server error on django page with contact form
I create my first page in django 2.2. I have implemented it on the apache server, but I have a problem displaying the page with the contact form. I receive a 500 error in response. I use the send_mail function to send messages. I checked the server logs. Unfortunately they don't tell me much. I added the {% csrf_token%} tag under the form tag in the html code. I think the problem is because of the wrong view for the page, but I don't know what to do to fix it. def contact(request): message = request.POST.get('message', False) sender = request.POST.get('email', False) subject = "New message from example.com form" + sender send_mail(subject, message, 'contact@example2.com', ['contact@example3.com'], fail_silently=False) return render(request=request, template_name="main/contact.html") Below, I paste the apache server log: [Thu Oct 24 10:47:28.394512 2019] [:error] [pid 17558] [client x.x.x.x] ModSecurity: Warning. Pattern match "^5\\d{2}$" at RESPONSE_STATUS. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_50_outbound.conf"] [line "53"] [id "970901"] [rev "2"] [msg "The application is not available"] [data "Matched Data: 500 found within RESPONSE_STATUS: 500"] [severity "ERROR"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "9"] [tag "WASCTC/WASC-13"] [tag "OWASP_TOP_10/A6"] [tag "PCI/6.5.6"] [hostname "example.com"] [uri "/contact/"] [unique_id "XbFlIH8AAQEAAESWGb4AAAAA"] [Thu Oct 24 10:47:28.397631 2019] [:error] [pid 17558] [client x.x.x.x] ModSecurity: Warning. Operator GE matched 4 … -
Django REST API query on related field
I have 3 models, Run, RunParameter, RunValue: class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField() class RunParameter(models.Model): parameter = models.ForeignKey(Parameter, on_delete=models.CASCADE) class RunValue(models.Model): run = models.ForeignKey(Run, on_delete=models.CASCADE) run_parameter = models.ForeignKey(RunParameter, on_delete=models.CASCADE) value = models.FloatField(default=0) A Run can have a RunValue, which is a float value with the value's name coming from RunParameter (which is basically a table containing names), for example: A RunValue could be AverageTime, or MaximumTemperature A Run could then have RunValue = RunParameter:AverageTime with value X. Another Run instance could have RunValue = RunParameter:MaximumTemperature with value Y, etc. I created an endpoint to query my API, but I only have the RunParameter ID (because of the way you can select which parameter you want to graph), not the RunValue ID directly. I basically show a list of all RunParameter and a list of all Run instances, because if I showed all instances of RunValue the list would be too long and confusing, as instead of seeing "Maximum Temperature" you would see: "Maximum Temperature for Run X" "Maximum Temperature for Run Y" "Maximum Temperature for Run Z", etc. (repeat 50+ times). My API view looks like this: class RunValuesDetailAPIView(RetrieveAPIView): queryset = RunValue.objects.all() serializer_class = RunValuesDetailSerializer permission_classes = [IsOwnerOrReadOnly]] … -
Django TruncDay limit by largest grouping
I am trying to draw a day series graph, whereby it will show the number of employees of the division(s) in a day series. The problem here is that I want to find a way to limit to the division with the most employees so I dont need to draw too many lines and stress the database. (for example limit it to top 3 division with the most employee attendance) I am using: Django 1.11.x Postgres 9.4 The goal is to create a day series graphing of this sort. has the grouping of division and the number of employee. I have manage to achieve it with the following code: from datetime import date, datetime from django.db.models import Count from django.db.models.functions import ( TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond, ) emp_by_day = Attendance.objects.annotate(day=TruncDay('created_at')).values('day', 'division_id').annotate(cnt=Count('employee_id', distinct = True)).order_by('day') for exp in emp_by_day: print(exp['day'], exp['division_id'], exp['cnt']) however, it currently output displays like this (i am generally happy but want to limit it): count<-> division_id<-> <---day-----------------> 2019-10-22 00:00:00+00:00 15 6 2019-10-22 00:00:00+00:00 16 6 2019-10-22 00:00:00+00:00 18 5 2019-10-22 00:00:00+00:00 20 4 2019-10-22 00:00:00+00:00 21 12 <-- largest 3 2019-10-22 00:00:00+00:00 25 14 <-- largest 3 2019-10-22 00:00:00+00:00 28 12 <-- largest 3 2019-10-23 00:00:00+00:00 … -
You cannot call `.save()` after accessing `serializer.data`
Error Showing when post data from API You cannot call `.save()` after accessing `serializer.data`.If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. My written Code is: serializerdata = serializers.CreateSerializer(data=request.data) if serializerdata.is_valid(): user_id = serializerdata.data.get('user_id') if user_id==2: serializerdata.save(i_created_by=request.user) return JsonResponse({"message": "success"}) else: return JsonResponse({"message": "user invalid"}) else: return JsonResponse({"message": "error"}) -
Django ManyToManyField with many same IDs
I'm trying to make a simple pizza order app in Django. I have 3 models (Toppings, Pizzas, Orders). In Orders model have ManyToManyField to Pizza. It's working fine if "user" orders one each pizza (Margarita and Pepperoni for example) but if order 2 Margarita in POST request I got only one Margarita ID in my result. How i can pass n-pizzas in one Order? My models looks like this: class Toppings(models.Model): name = models.CharField(blank=False, max_length=100, unique=True) class Meta: ordering = ['name'] def __str__(self): return self.name class Pizza(models.Model): name = models.CharField(blank=False, max_length=100, unique=True) ingredients = models.ManyToManyField(Toppings, blank=False, null=False) class Meta: ordering = ['name'] def __str__(self): return self.name class PizzaOrder(models.Model): created = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField(Pizza, blank=False, null=False) status = models.CharField(max_length=1, choices=[ (1, 'placed'), (2, 'approved'), (3, 'cooked'), (4, 'delivered'), (5, 'canceled') ], default=1) class Meta: ordering = ['created'] def __str__(self): return self.created I send POST with this data: { "items": [1, 1, 1, 2, 2], "status": 1 } and got this only 1 and 2 in items list (not 1,1,1,2,2): { "id": 2, "items": [ 1, 2 ], "status": 1 } -
Django-select2 is not showing model data
I have configured django-select2 but data from models is not showing in field. I had tried many methods like normal forms as well as modelform. I have also tried initialise the field as query, still its not working accordingly. Same code: forms.py class PricekeyForm(forms.ModelForm): uom = forms.ModelChoiceField( queryset=UnitOfMeasurement.objects.all(), widget=ModelSelect2Widget( model=UnitOfMeasurement, search_fields=['unit__icontains'] ) ) class Meta: model = Pricekey fields = ['uom', 'sales_price', 'return_price', 'damage_return_price',] def __init__(self, *args, **kwargs): self.fields['uom'].widget.queryset models.py class Pricekey(BaseModel): itemcode = models.CharField(max_length=255,null=True,blank=True) uom = models.ForeignKey('UnitOfMeasurement',on_delete=models.CASCADE,null=True,blank=True) sales_price = models.FloatField(null=True,blank=True) return_price = models.FloatField(null=True,blank=True) damage_return_price = models.FloatField(null=True,blank=True) expiry_return_price = models.FloatField(null=True,blank=True) What i wanted is, select2 filled with data from the db. Please tell me where i went wrong. I checked the documentation also for django-select2. please help me. -
Multiple Model File Uploader Using DRF
I have a models.py as the following and I'm trying to make multiple upload files in one request. and the other fields in the model i put the values in the back-end so, what i need exactly how to to send array of data (files) in one request and handle the files and create record for every single files separate? I also read a lot and see a lot of answers, but I felt the solution depends on the case maybe because I didn't got it will please any one can help me ? models.py file_name = models.FileField(upload_to='docs/', null=True, blank=True) created_by = models.ForeignKey(User, related_name='file_created_by', blank=True, null=True,on_delete=models.DO_NOTHING) created_date = models.DateTimeField(auto_now_add=True) serializers.py class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = '__all__' def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) user = kwargs['context']['request'].user super(FileSerializer, self).__init__(many=many, *args, **kwargs) def create(self, validated_data): validated_data['status'] = 'in_progress' self.context["file_name"] = self.context['request'].FILES.get("file_name") obj = File.objects.create(**validated_data) return obj views.py class FileCreateAPIView(CreateAPIView): queryset = File.objects.all() serializer_class = FileSerializer permission_classes = [IsOwnerOrReadOnly] def get_queryset(self): return File.objects.all() def perform_create(self, serializer): serializer.save(created_by=self.request.user, updated_by=self.request.user) -
How to choose my table for permissions in django?
Good day to all. I created a custom user model with custom permissions. I have several projects and permissions merged into one table. Is it possible to somehow set the table itself for these permissions?(like db_table = '"schema"."table"' to the models.) Google did not give answers. class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) email = CharField(unique=True, max_length=35, null=False, blank=False) class Meta: db_table = '"fyzzys"."users"' permissions = [ ("can_see_payments", "payments"), ("can_see_analytics", "analytics"), ] -
Classes in Django views.py - confused
I couldn't find the answer to my question here, which probably means I'm barking up the wrong tree. I have a Django site where I would like to create a page that uses BioPython to retreive the last x records from PubMed for a specific search string. The BioPython output is tricky, so to get the title and abstract I played around and wrote some test code that outputs a dictionary that could be looped over in a Django template. (thanks to Marco Bonzanini https://gist.github.com/bonzanini/5a4c39e4c02502a8451d) from Bio import Entrez from pmterm import term def search(query): Entrez.email = 'david.hallsworth@x.com' handle = Entrez.esearch(db='pubmed', sort='pubdate', retmax='20', retmode='xml', term=query) results = Entrez.read(handle) return results def fetch_details(id_list): ids = ','.join(id_list) Entrez.email = 'david.hallsworth@hotmail.com' handle = Entrez.efetch(db='pubmed', retmode='xml', id=ids) results = Entrez.read(handle) return results title_abstract = {} if __name__ == '__main__': results = search(term) id_list = results['IdList'] papers = fetch_details(id_list) for i, paper in enumerate(papers['PubmedArticle']): title = (paper['MedlineCitation']['Article']['ArticleTitle']) abstract = '' try: for a in paper['MedlineCitation']['Article']['Abstract']['AbstractText']: abstract += (a + " ") except KeyError: abstract = 'No abstract available' title_abstract[title] = abstract However, I now realise that I also want to store the citation and link url, so a dictionary probably isn't the way forward. In … -
How to make DRF serializer compatible with uppercase
My Boss decided to migrate Rest API from Java to Django. The previous Java guy designed every database field in camelCase, such as "userName", and every API POST data in camelCase. When I refactor these to DRF, I got following Model. The REST API also receive post data in camelCase, so I must lower the post data or is_valid() will return False. class Useraccount(models.Model): username = models.CharField(db_column='userName') REST API REQUEST DATA: { "userName": "Jenny" # I need lower "userName" to "username" } Is there a method to let DRF compitable with uppercase POST DATA? I don't want to lower these "userName" in every APIView. -
nginx: How can I remove port from url?
I have a vps server and domain Nginx /etc/nginx/sites-available/myproject and /etc/nginx/sites-enabled/myproject server { listen 80; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } /etc/nginx/nginx.conf ... http { ... include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*.*; } nginx -t - successful systemctl status nginx - active ufw status Status: active To Action From -- ------ ---- 8000 ALLOW Anywhere 80 ALLOW Anywhere 443 ALLOW Anywhere 8000 (v6) ALLOW Anywhere (v6) 80 (v6) ALLOW Anywhere (v6) 443 (v6) ALLOW Anywhere (v6) When I open ip of vps-server in browser I get home page of nginx. gunicorn /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/home/myproject ExecStart=/home/myproject/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-enabled# cat /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target systemctl status gunicorn - active gunicorn --bind 0.0.0.0:8000 myproject.wsgi - working /run/gunicorn.sock - exists Django /home/myproject/myproject/.settings.py ALLOWED_HOSTS = ['example.com', 'localhost'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test_db', 'USER': 'test_user', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '', } } I'm run a manage.py runserver example.com:8000 and get response from Django, that the server is started on example.com:8000. … -
Integrate legacy database to a new Django app
I developed a new cms using django and wagtail. News website that I developed the CMS for, used to use a php cms storing data in a messy and not normalized mysql database. So now, I have to store all old database records in my new django app's database. As the links to news in old cms were generated based on their ID and obviously the old links should keep pointing to the corresponding content, I have to keep IDs as well as other fields. Right now I am confused about what approach should I take in order to do the job. Basic idea is to use inspectdb generating a new model for records in old database, then write a script to fetch each object from old db, use it to generate an object of newly developed models and save the object in new database. What more efficient approaches can I take? -
How to convert 12 hr date time format to 24 hr format using java script?
I am sending the data from my database as 24 hr format, but when i use it on front-end for time counter as below the output gives 'none'. Also,When I print the 'plan_deactive_date' it shows time in 12 hr format. So, is there any way to convert the datetime from 12 hr format to 24 hr format? ''' <script> // Set the date we're counting down to var countDownDate = new Date("{{plan_deactive_date}}").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m … -
Custom Success Message in django Admin
I am trying to make custom Admin Successful messages but don't know how to do that I have a picture of successful message: https://i.stack.imgur.com/2SVuL.png -
Django Internal Server AWS Elastic-Beanstalk
I have a basic Django project that I am trying to deploy on an AWS Beanstalk instance. The Django project worked perfectly on my local machine but I am at my wits end with trying to get it running on AWS. I have tried multiple tutorials (the official AWS one, the Real Python and others) without success. I feel like im almost there, but after deploying to AWS with no ERRORs i get an "Internal Server Error" when i try the AWS generated URL. I am using the AWSEBCLI package from command prompt to deploy the project. Project was made using an Virtual Environment and im using a PC with Windows 10. Django Folder Structure (project name is wt): wt |.gitignore |db.sqlite3 |manage.py |Pipfile |requirements.txt ├+───.ebextensions ───|django.config ───|01_packages.config ├+───.elasticbeanstalk ├+───pages ├+───temp └+───wt ───|settings.py ───|urls.py ───|wsgi.py ───|__init__.py Before uploading, the project was git commit'd and python manage.py collectstatic'd and after the application and environment were created in AWS EB i added the AWS URL to the ALLOWED_HOSTS section of settings.py. requirements.txt: `Django==2.2.2 Pillow==6.2.0 psycopg2==2.8.4 pytz==2019.1 sqlparse==0.3.0` django.config: `option_settings: aws:elasticbeanstalk:container:python: WSGIPath: wt/wsgi.py` 01_packages.config: `packages: yum: git: [] postgresql93-devel: [] libjpeg-turbo-devel: []` I have uploaded the eb logs file here: https://gofile.io/?c=KMat86 Im really … -
Explanation for def update(self,instance,validated_data) in Django?
I am a fresher.I don't understand def update function Can any one explain def update function parameters in detail? Thanks in advance :) -
Ban enter to proceed with next question in Django survey
I am writing a short survey in Django. The last question sould be a Feedback form field in which participants can enter their thoughts. However, if I press enter while filling in the feedback, they proceed to the next question. I want to ban the proceeding with enter (just in case they want to write a lot). pages view: class Feedback(Page): form_model = 'player' form_fields = ['feedback'] models view: feedback = models.StringField( label='Is there any Feedback you would like to share?') -
Django OperationalError app cannot connect to Cloud App SQL
I have deployed my Django app to Google Cloud. It worked fine when I hosted it locally and throughout the steps outlined in this post. This is the full traceback. (Torque is the name of my project), and showroom is my app. OperationalError at /showroom/ (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Request Method: GET Request URL: https://torque-256805.appspot.com/showroom/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") Exception Location: /env/lib/python3.7/site-packages/MySQLdb/connections.py in __init__, line 166 Python Executable: /env/bin/python3.7 Python Version: 3.7.4 Python Path: ['/srv', '/env/bin', '/opt/python3.7/lib/python37.zip', '/opt/python3.7/lib/python3.7', '/opt/python3.7/lib/python3.7/lib-dynload', '/env/lib/python3.7/site-packages'] Server time: Thu, 24 Oct 2019 09:45:29 +0300 ... /env/lib/python3.7/site-packages/MySQLdb/__init__.py in Connect return Connection(*args, **kwargs) … ▶ Local vars /env/lib/python3.7/site-packages/MySQLdb/connections.py in __init__ super(Connection, self).__init__(*args, **kwargs2) … ▶ Local vars ... num_manufacturers = Manufacturer.objects.all().count() … ▶ Local vars The traceback refers to a views attribute. I never had this line of code when hosting it locally. -
its possible to use django mysql modal array filed
In my case i need design my modal in array of fields expected {field 1: string, field 2: [""], field 3: [""] } so far i designed my modal like following: class Collaborator(models.Model): name = models.CharField(max_length=50, blank=True, null = True, ) class Responsibility(models.Model): name = models.CharField(max_length=50, blank=True, null = True, ) class Class1(models.Model): field 1 = models.CharField(max_length=50, blank=True, null = True, ) field 2 = models.ManyToManyField(Responsibility, related_name='res_cards', blank=True,null=True ) field 3 = models.ManyToManyField(Collaborator, related_name='col_cards', blank=True, null=True ) so i am expecting for to get all fields in an array rather than define new modal