Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
install OpenFaaS to your Kubernetes Cluster on Minikube issue
while install OpenFaaS to your Kubernetes Cluster on Minikube getting some URL issue. C:\Users\XXX\openfaas\faas-netes>helm upgrade --install --debug --reset-values --set async=false --set rbac=false openfaas openfaas [debug] Created tunnel using local port: '60216' [debug] SERVER: "127.0.0.1:60216" Error: Non-absolute URLs should be in form of repo_name/path_to_chart, got: openfaas Help me to slove the following issue. -
Django with AngularJS
I would like to get an advice if what I am doing is right or not. I have a website where in the home page you search for items in the database, and when find your item, you press the name an you'll be taken to its details page. I know that Django gives the ability to send the selected item ID in the url and then I can render the details page and send the object in the context. But I want to receive the object as JSON in angularJS in the details page, so I am reading the url in the angular controller and then extracting the id and sending it to the views as an http request to get the item. I'll put an example code here: models: class Item(models.Model): name = models.CharField(max_length=50, null=False, blank=False) feature_1 = models.IntegerField(null=False, blank=False) feature_2 = models.IntegerField(null=False, blank=False) feature_3 = models.IntegerField(null=False, blank=False) def to_json(self): json_data = { 'id': self.id, 'name': self.name, 'feature_1': self.feature_1, 'feature_2': self.feature_2, 'feature_3': self.feature_3, } return json_data views: def home_page(request): return render_to_response('home.html', {}, context_instance=RequestContext(request)) def item_details_page(request): return render_to_response('item_details.html', {}, context_instance=RequestContext(request)) def get_item_details(request): item_id = int(json.loads(request.body)['item_id']) selected_item = Item.objects.get(pk=item_id).to_json() return JsonResponse({'item': selected_line}, content_type="application/json", safe=False) Angular controller ngApp.controller('ItemDetailsCtrl', ['$scope', '$rootScope', '$http', … -
Dajngo modelform filefield/imagefield createview
Model.py class NewInterfaceStepsDetails(models.Model): newinterfacestep =models.ForeignKey(NewInterfaceSteps, on_delete=models.CASCADE) details = models.CharField(max_length=50) doc = models.FileField(upload_to="static/attachments/doc/steps/" ,blank=True, null=True) pic = models.ImageField(upload_to="static/attachments/img/steps/" ,blank=True, null=True,) def __str__(self): return self.newinterfacestep.step.Step_name +'-'+self.details Form.py class NewInterfaceStepsDetailsForm(forms.ModelForm): class Meta model = NewInterfaceStepsDetails fields = ('newinterfacestep', 'details', 'doc','pic') def __init__(self, *args, **kwargs): rdid = kwargs.pop('reqstep_id', None) # pop the 'user' from kwargs dictionary super(NewInterfaceStepsDetailsForm, self).__init__(*args, **kwargs) view.py class NewRequestStepDetailView(CreateView): model = NewInterfaceStepsDetails form_class = NewInterfaceStepsDetailsForm success_url = reverse_lazy('request') template_name = 'new_requeststepdet.html' def get_form_kwargs(self): kwargs = super(NewRequestStepDetailView, self).get_form_kwargs() reqstep_id = self.kwargs['NewInterfaceSteps_pk'] kwargs['reqstep_id'] =reqstep_id return kwargs The images are not saving when running the above code. Kindly hel me to resolve this issue -
if user logout from social-auth then it automatically logout from the webapp
I am trying to do a work like this I have a django app which have login through google, i want a senario in which if the user logout from the google account then it should automatically logout from my app too. basically is there a way to sync this two. there is a decorator in django @login_required , which check if the user is login in my app only, i want it to check for if user is loggedin into the service provider also. -
django-admin How could i mark field readonly based on condition?
I have a model that i want to add 2 fields on it (1 field boolean and the other is float) i want to activate editing the float variable only if the boolean field is true other wise the float field show be disabled or readonly I tried to override get_readonly_fields but i couldn't make it work due to i can't do on change. here is my theory code : lass MyModelAdmin(BaseModelAdmin): def get_readonly_fields(self, request, obj=None): readonly_fields = super(MyModelAdmin, self).get_readonly_fields(request, obj) if obj.my_field: return readonly_fields + ['other_field'] return readonly_fields Note : My model is in inlines of other model and the relation is many2many so i want that when i added some lines it should be changing -
Django 1.11 FieldDoesNotExist at /host/2/delete/ | Room has no field named 'False'
In django, when i try to delete object via CBV (Class Based View), My Code: class HostDeleteView(DeleteView): """To perform delete action to the host.""" model = room_models.Room success_url = reverse_lazy('host:list') I'm getting the following error, FieldDoesNotExist at /host/2/delete/ Room has no field named 'False' Request Method: POST Request URL: http://127.0.0.1:8000/host/2/delete/ Django Version: 1.11.10 Exception Type: FieldDoesNotExist Exception Value: Room has no field named 'False' Exception Location:C:\Users\me\AppData\Local\Continuum\anaconda3\envs\python2_7\lib\site-packages\django\db\models\options.py in get_field, line 619 Python Executable: C:\Users\me\AppData\Local\Continuum\anaconda3\envs\python2_7\python.exe Python Version:2.7.14 What is wrong with my code ? -
How to use SQL query in django?
SELECT p.name, SUM(p.quantity) FROM hello_product p GROUP BY p.name; I want to use from this query to django code How do i use? -
Create database table from username
Using Django I have a form that shall save the parameters sent, into my database. I want to create a table which inherit it's name from the currently logged in user, and then passes the parameters into that table. I've looked around the web but haven't found something yet. Hope someone can help. Note: I know that the raw SQL down there is bad, but it's just so I can explain. Views.py from .models import replaceSettings from .forms import create_form def index(request): if request.method == 'POST': form = create_form(request.POST) if form.is_valid(): CREATE TABLE [IF NOT EXIST] %username form.save() replaceSettings() else: form = create_form() return render(request, 'form.html', {'form': form}) -
django serializer data extract nouns
I am trying to use nltk in my django rest app to extract nouns abd verbs: My WIP function looks like following: @api_view(['GET']) def test(request): verbs=[] tasks = Task.objects.all() serializer = TaskSerializer(tasks, many=True) print(serializer.data) text = nltk.word_tokenize(str(serializer.data)) tags = nltk.pos_tag(text) #print(tags) for tag in tags: if tag[1][0] == 'V': verbs.extend(tag) return Response(verbs) Line print(serializer.data) prints following: [OrderedDict([(u'id', 17), ('title', u'Browse through the list of books'), ('how_often', u'DO'), ('how_important_task', u'EI'), ('role', u'reader'), ('why_perform_task', u''), ('why_important_task', None), ('sequence_of_actions', u''), ('tools_used', u''), ('special_training_required', False), ('what_training_required', u''), ('what_can_go_wrong', u''), ('effects_of_task', u''), ('special_vocabulary_used', u''), ('people_involved', u''), ('any_improvements', u''), ('how_important_improvement', u''), ('benefits_of_improvement', u''), ('stakeholder', 2L), ('project', 1L)]), OrderedDict([(u'id', 18), ('title', u'Search for a book'), ('how_often', u'DS'), ('how_important_task', u'EI'), ('role', u'reader'), ('why_perform_task', u''), ('why_important_task', None), ('sequence_of_actions', u''), ('tools_used', u''), ('special_training_required', False), ('what_training_required', u''), ('what_can_go_wrong', u''), ('effects_of_task', u''), ('special_vocabulary_used', u''), ('people_involved', u''), ('any_improvements', u''), ('how_important_improvement', u'RI'), ('benefits_of_improvement', u''), ('stakeholder', 2L), ('project', 1L)]), OrderedDict([(u'id', 19), ('title', u'Request a book'), ('how_often', u'WO'), ('how_important_task', u'RI'), ('role', u'reader'), ('why_perform_task', u''), ('why_important_task', None), ('sequence_of_actions', u''), ('tools_used', u''), ('special_training_required', None), ('what_training_required', u''), ('what_can_go_wrong', u''), ('effects_of_task', u''), ('special_vocabulary_used', u''), ('people_involved', u''), ('any_improvements', u''), ('how_important_improvement', u''), ('benefits_of_improvement', u''), ('stakeholder', 2L), ('project', 2L)]), OrderedDict([(u'id', 26), ('title', u'See latest arrivals of the books'), ('how_often', u'MO'), ('how_important_task', u'LI'), ('role', … -
Multi Databases in django: misplaced tables
I have two postgres db in my project, one for every app: app1:Store, app2:Warehouse. Both of them have Order model which django names: store_order & warehouse_order (I am fine with that part); But after migrations there is a problem, both store_order and warehouse_order got in warehouse_db, also all these django tables I want to be only in store_db: settings.py DATABASES = { 'default': {}, 'store': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'store_db', 'PORT': 5432, }, 'warehouse': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'warehouse_db', 'PORT': 5432, } } DATABASE_ROUTERS = ['warehouse.router.WarehouseRouter', 'store.router.StoreRouter'] warehouse/router.py class WarehouseRouter: """ A router to control operations in warehouse app """ def db_for_read(self, model, **hints): if model._meta.app_label == 'warehouse': return 'warehouse' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'warehouse': return 'warehouse' else: return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'warehouse': return db == 'warehouse' return None store/router.py class StoreRouter: """ A router to control operations in store app """ def db_for_read(self, model, **hints): return 'store' def db_for_write(self, model, **hints): return 'store' def allow_migrate(self, db, app_label, model_name=None, **hints): return True warehouse/models.py also same as store/models.py except of app_label class Order(models.Model): id = models.CharField(max_length=128, null=False, unique=True, primary_key=True, default=uuid.uuid1) … -
ManyToManyField working on shell but not on server
This is the rarer behavior I've ever seen. I've got two ManyToMany relationships on a table: class Report(models.Model): ... companies = models.ManyToManyField(Company) customers = models.ManyToManyField(Customer) ... The form is a normal form with no custom save(). When I create a Report object through my webapp I can successfully query them on shell: In [3]: report.customers.all() Out[3]: <QuerySet [<Customer: xxxxxxx>]> But on server (I use gunicorn), no customers appears on the browser (through a regular ReportList based on generic.ListView) or in the server log when I query them, but companies field returns correct results on query. It looks to me at first that it could be some kind of conflict with another table or field, but I review all the possibilities and nothing apparently is wrong. -
How to add members to same chat room in Django Channels 2.1.1 using multichat example
Using Django Channels 2.1.1 and Django 2.0, I'm building a site where a customer presses a button and is brought into a chatroom with one staff in it. I'm beginning from Andrew Godwin's multichat example. I can't figure out how to properly add staff to group so that conventional two-way conversation can take place. I've read the documentation on layers, groups, and channels. I can't say I'm very clear on the concepts, but I figure a channel pertains to an individual user, a group pertains to a chatroom or its equivalent where users are somehow grouped together, and the layer is the medium through which communication takes place. Using this understanding, the best I've been able to do has been to add to the join_room(self, room_id) function like this, which is probably completely the wrong thing to do: async def join_room_client(self, room_id): ... # Added to find all staff who are logged in authenticated_staff = get_all_logged_in_users() # Added to list staff who are in less than 3 chatrooms available_staff = [] if len(authenticated_staff) > 0: for staff in authenticated_staff: if staff in users_and_rooms and len(users_and_rooms[staff]) in range(3): available_staff.append(staff) random_available_staff = random.choice(available_staff) # I thought receive_json() would look for "content", but … -
Update objects with DRF Serializer with data from JSON
I get a JSON response with data from multiple objects, run everything through the serializer and call serializer.save() which creates new objects but doesnt update the existing ones. view data = JSONParser().parse(request) serializer = CellCESaveSerializer(data=data, many = True, context = {'descriptoridlist' : descriptoridlist}, partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False) the serializer class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation(obj) # convert list to string return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.rstrip(",") # Needed because of JSON response data = data.split(",") # Split string to list data = [int(i) for i in data] # convert str to int did = self.context['descriptoridlist'] x = (did,data) # Create Array return super().to_internal_value(x) class CellCESaveSerializer(serializers.ModelSerializer): row = serializers.SlugRelatedField(slug_field="name",queryset=Descriptor.objects.all() ) # foreignkey mit namen val = StringArrayField() class Meta: model = CellCE fields = ('row','val') How can i update the existing objects without creating new objects? -
How to compress and uncompress files using lossless method using LZ4 in django rest framework
I came across the LZ4 documenttation but I have an an issue implementing it on django rest framework. I would like to compress a FileField how can I implement this? another question would be Is it a good idea to add the compress and decompress methods in models.py? -
I get an error when return a queryset objects: Cannot resolve expression type, unknown output_field
I'm need annotation each object in queryset. I used annotation, but when return modified object, I get this error: Cannot resolve expression type, unknown output_field. How solved this problem? def get_queryset(self): get_cinema = Ciname.objects.filter(active_cinema='t') distation = 54.87 #for example queryset = get_cinema.annotate(distance=models.Max(distation)) return queryset -
Objects filter with multiple choices in Django
Please help me a basic issues in Django. I want to get People objects who work as ADMIN and People objects who work as EDITOR in a Model People have field: role. My Model: GroupRoles = ( ('admin', 'Admin'), ('editor', 'Editor'), ('normal', 'Normal'), ) class People(models.Model): user = models.ForeignKey(User) role = models.CharField(max_length=40, choices=GroupRoles, default='normal') What i did: People.objects.filter(group=group, role={'admin', 'editor'}) But I get no object in queryset: [] Thanks in advance. -
Calling foreign key object several times in Django without several DB requests
Let’s say that I have a class Child linked, through a FK, to another class Parent. Now let’s say I have a block of code doing something like this in a template <td>{{ child.parent.name }}</td> <td>{{ child.parent.age}}</td> <td>{{ child.parent.address }}</td> My first question is, will Django go to the database and read the Parent entity three times? My second question is: if yes, what is the best practice not to read it multiple times? I mean I know I can declare an object before this block and set it equal to child.parent but is there another way to do that? -
Upload and Download excel file in Django
I want to create a web frame work Where I want to upload the excel file and then save and download the same excel file. if same excel file is uploaded 2 or 3 times or more while downloading this files should be named with some sumbers or so? with a download button how can i Do this I have written Upload code but I am not sure how to proceed with Download part can anyone help Views.py from django.shortcuts import render import openpyxl import settings def index(request): if "GET" == request.method: return render(request, 'myapp/index.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting all sheets sheets = wb.sheetnames print(sheets) # getting a particular sheet worksheet = wb["Sheet1"] print(worksheet) # getting active sheet active_sheet = wb.active print(active_sheet) # reading a cell print(worksheet["A1"].value) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) print(cell.value) excel_data.append(row_data) return render(request, 'myapp/index.html', {"excel_data":excel_data}) index .html <html> <head> <title> Excel file upload and processing : Django Example : ThePythonDjango.Com </title> </head> <body style="margin-top: 30px;margin-left: … -
how to plot webcam live video with its live histogram?
I want to create webapp using flask, in that i want to take video from webcam and plot its histogram on that same webpage. I searched a lot but i didn't get any answer about how to plot live histogram of video. i done it using cv2 and matplotlib , here is the code import numpy as np import matplotlib.pyplot as plt import cv2 capture = cv2.VideoCapture(0) fig, ax = plt.subplots() fig1, ax1 = plt.subplots() bins = 16 line_gray, = ax.plot(np.arange(bins), np.zeros((bins, 1)), color="black", lw=2) line_r, = ax1.plot(np.arange(bins), np.zeros((bins, 1)), color="red", lw=2) line_g, = ax1.plot(np.arange(bins), np.zeros((bins, 1)), color="green", lw=2) line_b, = ax1.plot(np.arange(bins), np.zeros((bins, 1)), color="blue", lw=2) ax.set_xlim(0, bins-1) ax.set_ylim(0, 1) ax1.set_xlim(0, bins-1) ax1.set_ylim(0, 1) plt.ion() plt.show() while True: _, frame = capture.read() numPixels = np.prod(frame.shape[:2]) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('Gray', gray) cv2.imshow("Color", frame) # print(type(cv2.calcHist([gray], [0], None, [bins], [0, 255]) )) histogram = cv2.calcHist([gray], [0], None, [bins], [0, 255]) / numPixels line_gray.set_ydata(histogram) b, g, r = cv2.split(frame) r_hist = cv2.calcHist([r], [0], None, [bins], [0, 255]) / numPixels g_hist = cv2.calcHist([g], [0], None, [bins], [0, 255]) / numPixels b_hist = cv2.calcHist([b], [0], None, [bins], [0, 255]) / numPixels line_r.set_ydata(r_hist) line_g.set_ydata(g_hist) line_b.set_ydata(b_hist) fig1.canvas.draw() fig.canvas.draw() if cv2.waitKey(1) & 0xFF == ord('q'): break capture.release() … -
django allauth : how can I get linkedin data - r_basicprofile, position_fields, location_fields
I'm using django-allauth==0.35.0 for sociallogin. (only linkedin, using OAUTH 2.0) Based on Linkedin developers documentation, (https://developer.linkedin.com/docs/fields) I tried to get Basic Profile Fields (r_basicprofile in allauth), also Location Fields and Position Fields if possible. I add SOCIALACCOUNT_PROVIDERS in settings.py like below, (I'm not sure how to add location and position, so I tried to add them below PROFILE_FIELDS) SOCIALACCOUNT_PROVIDERS = { 'linkedin': { 'SCOPE': [ 'r_emailaddress', 'r_basicprofile', 'r_fullprofile', ], 'PROFILE_FIELDS': [ 'id', 'first-name', 'last-name', 'positions', 'email-address', 'picture-url', 'public-profile-url', 'headline', 'skills', 'summary', 'location', 'industry', 'positions', 'company', 'specialties', 'public-profile-url', ], 'LOCATION_FIELDS': [ 'location', ], 'POSITION_FIELDS': [ 'company', ] } } Wierd thing is, when I got linkedin data, there's much missing fields. I only got emailAddress, firstName, id, LastName, publicProfileUrl, id. (here's sociallogin.serialize().get('account')) {'account': {'date_joined': None, 'extra_data': {'emailAddress': 'my_email@email.com', 'firstName': 'myname', 'id': 'xxxxx', 'lastName': 'kim', 'publicProfileUrl': 'https://www.linkedin.com/in/xxxxx'}, 'id': None, 'last_login': None, 'provider': 'linkedin_oauth2', 'uid': 'xxxx', 'user_id': None}, 'email_addresses': [{'email': 'my_email@email.com', 'id': None, 'primary': True, 'user_id': None, 'verified': False}], 'state': {'auth_params': '', 'process': 'login', 'scope': ''}, 'token': {'account_id': None, 'app_id': 2, 'expires_at': '2018-07-02T09:55:32.620Z', 'id': None, 'token': 'xxx', 'token_secret': ''}, I found much more field in Basic Profile Fields offered from linkedin (https://developer.linkedin.com/docs/fields/basic-profile) such as headline, summary, and so on. But nothing comes. What … -
Django tests admin forms inlines
I've an admin form for a job offer. To see all job responses for that offer, my form looks like this : class JobOfferAdminDisplayable(BaseTranslationModelAdmin): model = JobOffer inlines = [JobResponseInline,] class JobResponseInline(TabularDynamicInlineAdmin): model = JobResponse But I don't know how to test it... tried to include into post query the model's attributes + management form data but it's not working response = self.client.post(self.url, {"title_fr" : 'title', 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '1',"form-MAX_NUM_FORMS" : '2', "status" : 2, "email" :'email@email.fr', "type":'internship'}) This query generate the following error : django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] -
Django calculate percentages within group by
I have a model for which I want to perform a group-by on two values and calculate the percentages of each value per outer grouping. Currently I just make a query to get all the rows and put them into a pandas dataframe and perform something similar to the answer here. Although this works I'm sure it would be more efficient if I could make the query return the information I require directly. I am currently running Django 2.0.5 with a backend DB on PostgreSQL 9.6.8 I think window functions could be the solution as indicated here but I cannot construct a successful combination of annotate and values to give me the desired output. Another possible solution could be rollup introduced in PostgreSQL 9.5 if I can find a way to get the summary row as a set of extra columns for each row? But I also think it's not yet supported by Django. Model: class ModelA(models.Model): grouper1 = models.CharField() grouper2 = models.CharField() metric1 = models.IntegerField() All rows: grouper1 | grouper2 | metric1 ---------+----------+--------- A | C | 2 A | C | 2 A | C | 2 A | D | 4 A | D | 4 A … -
Customize default django password validators message
I am using default password validators from Django AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 6, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] I was wondering if there is a way to translate the text return by the function get_help_text() for each validator without creating new validators. -
extract nouns and verbs using NLTK
I have django rest application and a model Task. I am absolutely new to natural processing and I want to build a function that returns me list of nouns and verbs. It looks something like this: @api_view(['GET']) def noun_verb_list(request): nouns = [] verbs = [] """ List all nouns and verbs from available tasks """ if request.query_params.get('projectId'): # get a specific project projectId = request.query_params.get('projectId') project = Project.objects.get(id=projectId) tasks = project.project_tasks.all() # extract nouns and verbs from tasks here return Response(# return appropriate nouns) Could someone help me build this function? What to import and with logic? -
Django-Admin. Change the text of errors in the forms of adding and editing
Today I discovered a problem. In the form of adding or changing, when I enter duplicate data or leave the required field empty, I get an error with the text: "ModelName with this FieldName exists." And when FieldName is almost as hard as ModelName it looks a bit strange. I need to change the text error from the format: "ModelName with this FieldName exists." in the format: "ModelName with "FieldName" exists.". I tried to find this line with an error in the admin template "fieldset.html", but it is output as {{line.errors}}, which if you go higher from {{adminform}}. All errors are based on a specific template, how can I change it? All I need is to add quotes around FieldName