Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
API's of vCenter
We are using API's in our product to talk at vCenter. We are a quit new development team and want to update vCenter 6.5 to 6.7. I tried to find if this will have consequences for our code base in the form of deprecation or something. But I cant find anything regarding to this. Now this seem to mean that it should have no consequences. But before updating production I want to be sure. Does anyone has experience with this? -
Is there a way to programatically find which account has been locked out in django-axes?
I would like to check which accounts have been locked out in django-axes. I know this can be done in admin site, but can I get this in a view.py as well? -
How can i get the id of each record in ListApiView in DRF
I am facing an issue while getting the promary_ket(id) of record ListApiView in the Django rest framework. I am also implementing the Custom pagination. Here is my ListApiView Code: class TestList(ListAPIView): permission_classes = (IsAuthenticated, ) serializer_class = AllTestListSerializer pagination_class = CustomPagination def get_queryset(self): return TakeTestDetails.objects.filter(user=self.request.user).order_by('date', 'time').all() And here is my CustomPagination code: class CustomPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): response_data = { 'status': '200', 'message': 'Success', 'count': self.page.paginator.count, 'next': self.get_next_link(), 'previous': self.get_previous_link(), } if data: new_cycle_data = [] for row in data: row_dict = dict(row) print(row) cycle_id = row_dict['cycle_id'] cycle = TestCycle.objects.get(id=cycle_id) cycle_no = cycle.cycle_no cycle_start_date = cycle.cycle_start_date cycle_end_date = cycle.cycle_end_date cycle_start_date = change_date_format(cycle_start_date) cycle_end_date = change_date_format(cycle_end_date) test_date = change_date_format(row_dict['date']) row_dict['date'] = test_date row_dict['cycle_no'] = cycle_no row_dict['cycle_start_date'] = cycle_start_date row_dict['cycle_end_date'] = cycle_end_date new_cycle_data.append(row_dict) response_data['data'] = new_cycle_data else: return Response({ 'status': '404', 'message': "You haven't performed any test yet", 'count': self.page.paginator.count, 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'data': data }) return Response(response_data) Now what i want is also to get the primary_key/id of each row/record. But it's not giving me the id in data. How can i get the id? Thanks in advance -
Django: How to keep non-PII from removed users under GDPR
I'm using Django to build a B2B SaaS hobby project, where each company (tenant) can have many users and, eventually, remove them. It's important to keep the reason why a user was removed. The straightfoward way for this to be solved would be to turn is_active to False and add a reason_for_removal field on the User model. Then make sure is_active is indexed (is it by default in Django?) and all querysets are appropriately filtered. However, in a GDPR world, is this the right way to do it? Does it make sense to create a separate model called RemovedUser just with the user and reason_for_removal fields (and no other Personal Identifiable Information) and delete the original user instance? -
python requests taking 100% of cpu
One of our API servers has an issue with CPU usage. API is written in python and configured in ubuntu aws EC2 instance. This application uses Python 2.7 and Django 1. This can be accessed through port 80 by proxy passing. Sometimes we are getting 499 requests in our logs that time $htop value shows 100% cpu usage in the server. Only python requers are running in this server. But in aws cloudwatch monitoring it is not. only 40% to 50%. PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 23086 root 20 0 815776 96056 12792 S 100 4.7 2:43.12 python 24041 root 20 0 292756 92820 12696 S 8.0 4.5 0:33.73 python 24072 root 20 0 815656 95696 12792 S 5.3 4.7 0:28.27 python Please help TIA -
Django formtools how to store form data between logout/login cycles
I am using django-formtools to split a long form in parts. This is working fine. However, I want users to be able to start filling the form going until let's say step 5 out of 9, then logout and login again and continue filling the form from step 5 on. I can do this with cookies but, if user A starts filling the form then logs out and then user B logs in, user B can see the data of user A if user B chooses to continue filling the form. This happens if users A and B use the same computer and web browser. This, of course, cannot happens. If I use sessions instead of cookies then when a user logs out it is not possible to continue filling the form from step 5 on because the session is flushed and the data deleted. So I guess that sessions will not help me here. In order to continue filling the form from step 5 on I override the get method of django-formtools.WizardView: def get(self, request, *args, **kwargs): """ To allow resume editing of a session storaged submissions """ if self.continue_fill == True: try: return self.render(self.get_form()) except Exception as e: … -
How to create multiple users in Django without letting them access each other's data
I am not quite sure if the title I used for my question is the right one. And if this has previously been answered, someone should please point me to it as I have tried so much to find that out but its been futile. I am currently working on a basic HR system which can be used by different companies. In a much clearer way, how can I create an online system whereby multiple companies can manage their employees online without having access to each other's data? And without even knowing that they use the same system? A perfect example of this kind of system is "Zoho People". -
i want to try to implement activation hash in Django using python 3.x
import random import base64 import hmac import hashlib short_hash = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest() username='hp' activation_key = hashlib.sha256(short_hash + username).encode('utf-8').hexdigest() short_hash = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()[:5] username="hp" activation_key = hashlib.sha256(short_hash + username).hexdigest() Traceback (most recent call last): File "", line 1, in TypeError: Unicode-objects must be encoded before hashing -
Django Rest API - custom layout for xml Render
Im having trouble formatting XML output for a specific render. I need to have the XML format outputted like the below sample: <mappings> <mapping> <subnet from="192.168.1.1" mask="255.255.255.0"/> <location country="United States" region="California" city="San Francisco"/> </mapping> <default country="United States" region="California" city="San Francisco"/> </mappings> Ive tried two methods thus far both have failed, how can I achieve this xml output? Thanks First I create json fields in serialiser and create the json dict manually for subnet and location like below Serializer class SerializerDataGeoMapping(serializers.Serializer): subnet = serializers.JSONField() location = serializers.JSONField() View class DataGeoMapping(generics.ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = SerializerDataGeoMapping paginate_by = 20 def get_queryset(self): queryset = SiteSupernet.objects.filter(site__is_live=True, subnet_type__subnet_type__icontains='site aggregate' ).select_related( 'site', 'site_type', 'subnet', 'subnet__subnet_type' ).values( 'site_id', 'mask', 'subnet', location=F('site__location'), country=F('site__country'), region=F('site__region'), city=F('site__town'), location_type=F('site__site_type__site_type'), ) for supernet in queryset: supernet['subnet'] = {"from" : supernet['subnet'], "mask" : supernet['mask']} supernet['location'] = {"country" : supernet['country'], "region" : supernet['region'], "city" : supernet['city']} output <root> <list-item> <subnet> <from>10.1.1.0</from> <mask>/24</mask> </subnet> <location> <country/> <region/> <city>Aberdeen</city> </location> </list-item> <list-item> <subnet> <from>10.3.3.0</from> <mask>/24</mask> </subnet> <location> <country/> <region/> <city>Edinburgh</city> </location> </list-item> ... Second I tried creating a full dictionary and using that as json field serializer class SerializerDataGeoMapping(serializers.Serializer): mappings = serializers.JSONField() default = serializers.JSONField() view class DataGeoMapping(generics.ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = SerializerDataGeoMapping paginate_by … -
Dynamic select box in Django template without using JavaScript
I have a template page which displays a database table. The implementation I would like here is to have a set of select boxes to set filter parameters, then have a button to apply the selected filters. The problem here is some of my categories are a bit out of control with the amount of options available. So I would like to be able to select an option from selectbox1 and depending on the choice, the options in selectbox2 are filtered down by eliminating any null combinations. I reckon this is a fairly easily solved problem if I included some JavaScript in my solution but I want to know if there is a relatively tidy method of doing this purely within Django Views + Templates. -
Django - JupyterHub - OAuth2 - Jupyter Notebook Interaction
I have a rather complex requirement. Here is what I hope to achieve. A Django backend that shall host all kinds of information about the user of a service. User will log into Django backend and can send some instructions or query to the service. OR The user can access a Jupyter notebook from within the Django app and use an API to communicate the query to the service. This might be a preferred mode of accessing the service since the results are something that need further analysis using Python. Whether it is a query sent using a form within the Django service OR whether query is sent using a Python API from within a notebook, it is sent to the same web URL/endpoint so that the query can be logged etc. This URL is protected by authentication. Now, what I have managed to do so far is the following: Configure Django to provide OAuth based authentication. Configure JupyterHub to communicate with Django and start a user specific notebook server. I have even figured out how to use Jupyter Notebook Extensions to pre-populate any new notebook with the relevant code and comments that will help the user use our API. … -
Integrate sweatalert2 in django as python package
How to ingrate sweat-alert in a django application as a python package ( installing via pip) and pass it into views -
Unable to get the third-level dropdown list options using django modelform and ajax
I'm trying to create a chained dropdown-list for Indian administrative levels (State --> District --> City) My Model and ModelForm is like this: models.py: # I've pre-loaded using foreignkeys from models State, District and City in another app in the same project folder class LocationChainForIndia(Model): state = ForeignKey(State, on_delete=CASCADE) district = ForeignKey(District, on_delete=CASCADE) city = ForeignKey(City, on_delete=CASCADE) --------------------------- forms.py: class LocationChainIndiaForm(ModelForm): class Meta: model = LocationChainForIndia fields = ['state', 'district', 'city'] def __init__(self, *args, **kwargs): super(LocationChainIndiaForm, self).__init__(*args, **kwargs) self.fields['state'].queryset = State.objects.all().order_by('name') self.fields['district'].queryset = District.objects.none() self.fields['city'].queryset = City.objects.none() if 'state' in self.data: state_id = int(self.data.get('state')) self.fields['district'].queryset = District.objects.filter(state_id=state_id).order_by('name') elif self.instance.pk: self.fields['district'].queryset = self.instance.state.district_set.order_by('name') if 'district' in self.data: district_id = int(self.data.get('district')) self.fields['city'].queryset = City.objects.filter(district_id=district_id).order_by('name') elif self.instance.pk: self.fields['city'].queryset = self.instance.district.city_set.order_by('name') Views are written as: def request_india_data(request): if request.method == "POST": form = LocationChainIndiaForm(request.POST) if form.is_valid(): form.save(commit=False) state = form.cleaned_data.get('state') district = form.cleaned_data.get('district') city = form.cleaned_data.get('city') pprint({'state': state, 'district': district, 'city': city}) else: form = LocationChainIndiaForm() context = {'form': form} return render(request, 'india/request_india_data.html', context=context) def districts_for_state(request): state_id = request.GET.get('state') districts = District.objects.filter(state_id=state_id).order_by('name') context = {'districts': districts} return render(request, 'india/districts_for_state.html', context=context) def cities_for_district(request): district_id = request.GET.get('district') cities = City.objects.filter(district_id=district_id).order_by('name') context = {'cities': cities} return render(request, 'india/cities_for_district.html', context=context) HTML templates for districts_for_state, and cities_for_district are in … -
Render list of lists elements in django html
I have list of lists like this in django view: res = [['Adam','334','Ford'],['Steve','130','Porsche'],['Dave','510','Ford']] I want to display for example Adam, 334, Ford in table cells {% for n in data %} {% for k in n %} <table style="border:1px solid black;margin-top:15px;width:100%"> <tr> <td style="width:33%;border:1px solid black;"> {{ k.0 }} </td> <td style="width:33%;border:1px solid black"> {{ k.1 }} </td> <td style="width:33%;border:1px solid black"> {{ k.2 }} </td> </tr> </table> {% endfor %} {% endfor %} Type of res is list and printing res[0][2] - gives Ford, but in table I get - k.0 = A k.1 = d k.2 = a With one for loop I get triple printing of res[0] in k.0/1/2 -
AttributeError: module 'django.contrib.auth' has no attribute 'models'. what am I missing?
when I run the migration in django the terminal says AttributeError: module 'django.contrib.auth' has no attribute 'models'.I'm following lectures in django 1.1 where Im actually using django 2.2. views.py def calicutpara(request): return render(request, 'calicutpara.html') class signup(CreateView): form_class = forms.userCreateForm success_url = reverse_lazy('login') template_name = 'signup.html' app urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'login' urlpatterns = [ path('ktupage/', views.ktupage, name='ktupage'), path('mgcourses/', views.mgcourses, name='mgcourses'), path('calicutcourses/', views.calicutcourses, name='calicutcourses'), path('mgcourses/mgaas/', views.mgaas, name='mgaas'), path('mgcourses/mgpara/', views.mgpara, name='mgpara'), path('calicutcourses/calicutaas/', views.calicutaas, name='calicutaas'), path('calicutcourses/calicutpara/', views.calicutpara, name='calicutpara'), path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(),name='logout'), path('signup/', views.signup.as_view(),name='signup'), ] models.py from django.db import models from django.contrib import auth class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class userCreateForm(UserCreationForm): class Meta: fields = ('username', 'email', 'password1', 'password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = 'E-mail Address' -
Prevent collectstatic from trying to access a database
I have a Dockerfile with a multi-stage build in which I'm trying to run collectstatic to get all the static files and copy them into the final docker image. At this moment I don't have a database to access, but as collectstatic is trying to access one with dummy values, I get an error. In my opinion there should be no need for collectstatic to access a database. I have read through some Issues concerning this and I think that the maintainers of django are not planning on changing this. That's why I need to know if there is any way to prevent this access to a database. Here's what I have: ARG baseImage FROM ${baseImage} AS base USER root ENV DB_HOST="example" \ DB_NAME="example" \ DB_USER="example" \ DB_PASSWORD="example" RUN python app/manage.py collectstatic --skip-checks --noinput --clear \ && node_modules/.bin/gulp compile --destination "/tmp/staticcmp" FROM nginx:1.11 AS cdn COPY docker/cdn/etc/cdn-nginx.conf /etc/nginx/conf.d/default.template COPY docker/cdn/robots.txt /usr/share/nginx/html/robots.txt COPY docker/cdn/bin/ /usr/local/bin/ COPY --from=base /tmp/staticcmp/ /usr/share/nginx/html/static ENV NGINX_ERROR_LOG="/dev/stdout" \ NGINX_ACCESS_LOG="/dev/stdout" EXPOSE 8000 ENTRYPOINT ["docker-cdn-entrypoint"] -
Filter Django ResourceRelatedField's queryset
In our project we are using ResourceRelatedField for a foreign key field in one of our serializers to comply with JSON:API format. This is how it looks: types = ResourceRelatedField( queryset=Type.objects, many=True ) The problem that I have is that I want to exclude some of the items from the queryset of this field so that I don't get all the items from the Type model, but a subset. If I write something like this it doesn't work: types = ResourceRelatedField( queryset=Type.objects.exclude(id=13), many=True ) Didn't find anything related in the documentation. -
trying to change a .mov file to .mp4 when uploading it - python/django
first time asking a question here... so, I have a django web app where people can upload video files. The video file upload just fine and when they are .mp4 files, they can click on them and immediately play them in the chrome browser. However, if the video file is .mov, it forces the user to download the file to their computer before viewing it. I have tried to capture the file before is saves and change the filename from .mov to .mp4 but its not working. form = AddAttachmentForm(request.POST, request.FILES) if form.is_valid(): attachment = form.save(commit=False) attachment.user = student attachment.attacher = self.request.user attachment.date_attached = timezone.now() attachment.competency = competency attachment.filename = request.FILES['attachment'].name if attachment.filename.endswith('.mov'): attachment.filename.replace('.mov','.mp4') attachment.save() -
A field with precision 10, scale 2 must round to an absolute value less than 10^8
I have a django-field total_price in postgres database with version 9.3.11. Here is the current code for it. total_value = models.DecimalField(decimal_places=100, default=0, max_digits=300) I want to convert it to proper 2 decimal place. So I wrote this code total_value = models.DecimalField(decimal_places=2, default=0, max_digits=10) My migration file # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('my_table', '0040_my_table_skipped'), ] operations = [ migrations.AlterField( model_name='my_table', name='total_value', field=models.DecimalField(default=0, max_digits=10, decimal_places=2), ), ] When I run command python manage.py migrate It shows me this error A field with precision 10, scale 2 must round to an absolute value less than 10^8. Any idea what is this about ? -
Django app giving error after deployed on Heroku
I have deployed the Django app on heroku and giving the error: OperationalError at / could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I have in setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'LP7Website', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432' } } App link is: https://lp7.herokuapp.com/ How to solve..? -
Django search_field
How to solve this error? cause whenever I search the student user I received an error, error admin.py @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): #inlines = [InLineSubject] list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year') #list_select_related = ('Student_Users') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') search_fields = ('Student_Users',) def lrn(self, obj): return obj.Student_Users.lrn my models.py class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) -
How to run django project in Aws ec2 ubuntu
I have created a django application and uploaded in to Ec2. I can access the site using public IP only when I run the python manage.py in aws command line. If I close the putty window I am not able to access the site. How can I make sure that the site is available always even if i close the command line / putty. I tried WSGI option but its not working at all. Appreciate your help to give us a solution to run the python applicaiton in AWS -
Are celery tasks and queues interrupted when elastic beanstalk EC2 instances are removed?
I have a Django app running on Elastic Beanstalk in a Multicontainer Docker platform. So each EC2 instance has Docker containers for Django, Celery, RabbitMQ and Nginx. I have concerns regarding celery tasks when an EC2 instance is removed due to an auto-scale event or an immutable deployment. Will current tasks in the celery queue be lost when an instance is removed? Can a running celery task be interrupted on an instance removal? Celery beat schedule (cron) would be called from every new instance launched, causing duplicated calls. I'm curious if anyone else has experience solving the above? Here's a list of some of the solutions I'm thinking about: Change the celery broker to a remote ElastiCache Redis instance. Not sure that would work tho. Use another library to replace Celery which can store the tasks in the DB (e.g. huey or apscheduler). Migrate from celery to AWS SQS + Elastic Beanstalk Worker. That would mean duplicating the same codebase to be deployed to both the current web as well as a worker Elastic Beanstalk. Any other ideas or concerns? -
How to assign query result value by column in django
The output of mysql query in django is shown below. -- views.py -- def result(): cursor = connection.cursor() try: cursor.execute( "select b.date, a.value from t1 a join t2 b on a.id = b.id" result = cursor.fetchall() finally: cursor.close() return result -- result -- ((datetime.date(2019, 4, 25), '8192'), (datetime.date(2019, 5, 25), '8192'), (datetime.date(2019, 6, 25), '8192'), (datetime.date(2019, 11, 25), '8192')) I want to assign a value to a variable like this x = data y = value What should I do? Please let me know. -
pull data from two tables with one query
I want to pull data from two tables with one query. I try with the following code but it doesn't fetch the data from the first table. How do I fix this? ` class DebtFinancialReceivedAmountListAPIView(ListAPIView): permission_classes = [IsOwner] filter_backends = [django_filters.rest_framework.DjangoFilterBackend] def get(self, request): spen = Spending.objects.filter( createdDate__gt=(self.request.query_params.get('startingDate')), createdDate__lt=(self.request.query_params.get('endDate'))) \ .aggregate( spendingAmount=Sum('spendingAmount'), spendingKdv=Sum('spendingKdv'), spendingTotal=Sum('spendingTotal')) result = Debt.objects.filter( paymentDate__gt=(self.request.query_params.get('startingDate')), paymentDate__lt=(self.request.query_params.get('endDate')))\ .aggregate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')) return Response(spen, result) `