Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running facial recognition script in Django
I have a facial recognition script in my django app, below is the code, It returns a string which is the name of the person found. The script works well on its own when i pass an image parameter to it. I want to run this script in my views.py so when i get a name, i search for the name in my models then get a matching result. The templates loads just fine but after uploading the image and i submit no action take place. def identify_face(imagename): known_face_encodings = [] known_face_names = [] known_faces_filenames = [] for (dirpath, dirnames, filenames) in os.walk('assets/img/users/'): known_faces_filenames.extend(filenames) break for filename in known_faces_filenames: face = face_recognition.load_image_file('assets/img/users/' + filename) known_face_names.append(re.sub("[0-9]",'', filename[:-4])) known_face_encodings.append(face_recognition.face_encodings(face)[0]) face_locations = [] face_encodings = [] face_names = [] imagename_new = face_recognition.load_image_file(imagename) face_locations = face_recognition.face_locations(imagename_new) face_encodings = face_recognition.face_encodings(imagename_new, face_locations) face_names = [] for face_encoding in face_encodings: matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" face_distances = face_recognition.face_distance(known_face_encodings, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = known_face_names[best_match_index] face_names.append(name) return name This is my forms.py and views.py code forms.py from django import forms class ImageUploadForm(forms.Form): image = forms.ImageField() views.py from .models import MyData from cisdb.forms import SearchForm,ImageUploadForm from django.contrib.postgres.search import SearchVector from cisdb.face_recogniton_script import identify_citizen def … -
I deployed this code, but its taking input only from my device
enter link description here After clicking the voice icon start giving voice input. I want to take users output. but when some one click on the voice icon, it doesn't take input from their device instead take input from my device.enter image description here def voice_recognition(request): #print("Version is", s_r.__version__) #print(s_r.Microphone.list_microphone_names()) r = s_r.Recognizer() mic = s_r.Microphone(device_index = None) with mic as source: print("Speak after half second!!!!") r.adjust_for_ambient_noise(source) #reduce noise audio = r.listen(source, timeout = 30) #take voice input from the microphone #r.recognize_google(audio) #to print voice into text text = r.recognize_google(audio) -
Error - dictionary update sequence element #0 has length 10; 2 is required
Models.py class LeaveTransactionLog(models.Model): empno = models.ForeignKey(Employee,related_name='ltl_empno',on_delete=models.PROTECT) approver_mgrno = models.IntegerField(default=0) applied_year = models.IntegerField(default=2019) applied_date = models.DateTimeField(auto_now_add=True) leave_type = models.CharField(max_length=2,choices=leave_choices,default='PL') leave_start_date = models.DateField() leave_end_date = models.DateField() leave_days = models.IntegerField(default=0) leave_decision = models.CharField(max_length=2,choices=decision_choices,default='ES') forms.py class ApproveRejectEscalateForm(forms.ModelForm): # this method is implicitly called when form validation occurs on use of form.is_valid() call. # can also be used to transform values received on form before a save is fired to DB. def clean(self): self.cleaned_data = super(ApproveRejectEscalateForm, self).clean() return self.cleaned_data class Meta: model = LeaveTransactionLog fields =['empno','approver_mgrno','applied_year','leave_type','leave_start_date','leave_end_date','leave_days','leave_decision'] Views.py class ApproveRejectEscalateFormView(View): def get(self, request): ARE_formset = modelformset_factory(LeaveTransactionLog, fields=( 'empno', 'approver_mgrno', 'applied_year', 'leave_type', 'leave_start_date', 'leave_end_date', 'leave_days', 'leave_decision'),max_num=2,min_num=0,form=ApproveRejectEscalateForm) formset = ARE_formset() return render(request,'ApproveRejectEscalateForm.html',{'formset':formset}) def post(self,request): qset = LeaveTransactionLog.objects.all().values() print(qset) responseformset = ApproveRejectEscalateForm(request.POST,initial=qset) if responseformset.is_valid(): print('Form valid !') formdata = responseformset.cleaned_data iteration = 1 for f in responseformset: print('Employee details :',iteration) print('Employee number :',formdata.empno) iteration = iteration + 1 else: print('Form Invalid !') print(responseformset.errors) print(responseformset.non_field_errors()) return render(request, 'LeaveApplicationhome.html') The following two lines are the source of the error.. qset = LeaveTransactionLog.objects.all().values() responseformset = ApproveRejectEscalateForm(request.POST,initial=qset) If I use the queryset after extracting the values and then pass it to the initial param of the formset, then the error says - "dictionary update sequence element #0 has length 10; 2 is required" … -
DRF options request on viewset with multiple serializers
I'm using a mixin on my viewset so that different viewset actions and any custom actions will use a different serializer. I have an extra action called invoice which is just a normal update but using a different serializer. I need to perform an OPTIONS request at the endpoint to get options for a <select> element. The problem is that when I perform the request it's picking up the serializer from the default update - OrderSerializer instead of InvoiceSerializer. How can I pick up the options from the correct serializer? class MultipleSerializerMixin: """ Mixin that allows for multiple serializers based on the view's `serializer_action_classes` attribute. ex. serializer_action_classes = { 'list': ReadOnlyListSerializer, 'retrieve': ReadOnlyDetailSerializer, } """ def get_serializer_class(self): try: return self.serializer_action_classes[self.action] except (KeyError, AttributeError): return super().get_serializer_class() class OrderAPIViewSet(MultipleSerializerMixin, viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = serializers.OrderSerializer serializer_action_classes = { 'invoice': serializers.InvoiceSerializer, } @action(detail=True, methods=['put'], url_name='invoice') def invoice(self, request, *args, **kwargs): """ Invoice the order and order lines. """ return self.update(request, *args, **kwargs) -
django Postgres ArrayField preserving list insert ordering
I am looking to use an ArrayField in Django, and I was wondering if this field preserves the order of insertion. So, for example, if I insert the list: ["stackoverflow", "is", "awesome"] I would like to have the exact same ordering when I retrieve this pkid. I have looked around the django docs and I see no mention of preserving insert order and hence my question. It would be great if someone can link me to the django docs for this. PS: I presume JSONField will NOT preserve order and thus looking into ArrayField. -
html output from a django manytomany field with for
i have a many to many relationship like in this model class A(models.Model): name = models.CharField(max_length=250) class B(models.Model): name = models.CharField(max_length=250) bla = models.ManyToManyField ('A') now i would like to output all relationships in the html I have a view like: def showview(request): b = B().objects.all() return render(request, '/bla.html', {'b': b}) and the html like: {% for ab in b %} b.name {% for a in ab.bla %} a.name {% endfor %} {% endfor %} but i get the error? 'ManyRelatedManager' object is not iterable -
Why django template is not showing any output?
So, here I was writing a simple news app using django, but template does not seem to be working,it's not showing any output that has been passed from views.py. I have checked settings.py,INSTALLED_APPS settings it's working views.py from django.shortcuts import render,HttpResponse import bs4 from bs4 import BeautifulSoup as soup from urllib.request import urlopen def get_news(): news_link = "https://news.google.com/news/rss" page = urlopen(news_link) xml_page = page.read() page.close() soup_page = soup(xml_page,"xml") news_list = soup_page.findAll("item") return news_list def index(request): news_list = get_news() return render(request,'main/index.html',{'news_list' : news_list}) and template {% for news in news_list %} <h3> {{ news.title.text }} </h3> <h3> {{ news.pubDate.text }} </h3> {% endfor %} If I pass any other data from render() dictionary, it is working but when passing lists,it's not showing any data in template I tried checking if the list is None or empty but no,it's not empty. Thank you! -
(1048, "Column 'organisation_id' cannot be null") error but model is defined that it can be null
I'm getting the following error (1048, "Column 'organisation_id' cannot be null") when saving a model but the field within the Django model is defined such that it can be null organisation = models.ForeignKey( to='Organisation', on_delete=models.CASCADE, related_name='organisation_admin', null=True, ) Why? -
How can I get X variable from user in Django
enter image description here I wanna get this variable ( X ) from user , how can I do it ?! -
How to run the django-admin check command?
I just installed Django and am trying to run it for the first time. For now, all I did is pip3 install Django and django-admin startproject Right after installing it, I ran manage.py check and django-admin check. manage.py check displayed no issues, but django-admin check output was : django.core.exceptions.ImproperlyConfigured: Requested setting ROOT_URLCONF, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I understand I must edit the environment variable, but What should its value be ? What did I possibly do wrong to get this Error ? -
Django: Time Interval for auto fill in model
I need help for my web apps. Here is the scenario, the apps allow the user to upload the excel file provided from the web itself. Once they uploaded the file, I need to autofill into my model which batch they are based on the time. Here is the detail of the batch: Batch 1: 08:00 - 09:59 Batch 2: 10:00 - 13:59 Batch 3: 14:00 - 16:59 What is the best way to achive this ? Thanks -
query to fetch x who's y have max average and y should be greater than 10
Models.py class Student(models.Model): id = models.AutoField(primary_key=True) stud_name = models.CharField(max_length=255) cgpa = models.IntegerField() class Teacher(models.Model): id = models.AutoField(primary_key=True) teach_name = models.CharField(max_length=255) student = models.ManyToManyField(Student) what will be query to fetch Teacher's name who's student have the max average and number of students should be greater than 10 ?(I also need the count and average). -
Very slow loading model in Django Admin and DRF API
I have a model with 11 million instances (there are no problems when I test the model on a small amount of data). The model does NOT have any ForeignKey or ManyToMany fields. When I try to load a page with my model (DRF API or Django Admin) the page loads for about 5-7 minutes, also the whole system starts to slow down. When i'm working with other models there is no such problem. Model: class MyModel(models.Model): process_number = models.CharField(max_length=255, blank=True, null=True) order_number = models.CharField(max_length=64, null=True, blank=True) dep_name_l1 = models.CharField(max_length=128, null=True, blank=True) worksite = models.CharField(max_length=64, null=True, blank=True) date_create = models.DateTimeField(null=True, blank=True) date_end = models.DateTimeField(null=True, blank=True) date_close = models.DateTimeField(null=True, blank=True) client_type = models.CharField(max_length=254, null=True, blank=True) account = models.CharField(max_length=32, null=True, blank=True) address_full = models.CharField(max_length=4000, null=True, blank=True) work = models.CharField(max_length=4000, null=True, blank=True) mark_value = models.IntegerField(null=True, blank=True) mark_by_serv = models.IntegerField(null=True, blank=True) mark_by_add = models.IntegerField(null=True, blank=True) area = models.CharField(max_length=4000, null=True, blank=True) building_type = models.CharField(max_length=2, null=True, blank=True) mrf_name = models.CharField(max_length=16, null=True, blank=True) filial = models.CharField(max_length=128, null=True, blank=True) order_status = models.CharField(max_length=128, null=True, blank=True) given_main_works_amount = models.FloatField(blank=True, null=True) checked_main_works_amount = models.FloatField(blank=True, null=True) is_difference_of_main_works = models.BooleanField(default=False) given_additional_works_amount = models.FloatField(blank=True, null=True) checked_additional_works_amount = models.FloatField(blank=True, null=True) is_difference_of_additional_works = models.BooleanField(default=False) calculated_all_works_amount = models.FloatField(blank=True, null=True) checked_all_works_amount = models.FloatField(blank=True, null=True) is_difference_of_all_works = models.BooleanField(default=False) is_matching_the_manual … -
TemplateDoesNotExist at /accounts/login/
I'm following a small website clone project on Udemy, but ran into a problem and can't seem to find any solutions to it. The index.html works fine but when I click on the "log in" link, I get an error of "TemplateDoesNotExist at /accounts/login/". I'm using python 3.7.5 and django 3.0.2 for this. I'll provide some images of my directories and files for more details. HELP!! -
pipenv shell Launching subshell in virtual environment… 'powershell.exe' is not recognized as an internal or external command, operable program or
I am using Windows 10, and Visual Studio Code terminal (but I tried also Windows Powershell). This is my location: PS C:\Users\MyUsername\Desktop\MyProjectFolder> This was successful: pip install --user pipenv This was successful: pipenv install django At the end I get the message: To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. So I run: pipenv shell and get only this message: Launching subshell in virtual environment… 'powershell.exe' is not recognized as an internal or external command, operable program or batch file. I have searched for duplicate questions but could not find anything helpful. -
Extending user view in django admin
I extended my user model to create two profile types, a mentor profile and a student profile. These profiles have the standard username, password and email info along with other information I included, some specific to one user type. However, when I login to my admin, while I can see the list of users, I cannot see any other information aside from username, email, firstname, lastname and permissions (active, staff status and superuserstatus). I would like to see all the information I created in the customer user models, what type of profile the user has created (teacher or student) and whether I have activated the profile. This is my models.py: ... class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_activated = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='mentor') linkedin = models.URLField(max_length=200,null=True,blank=True) photo = models.ImageField(null=True, blank=True, upload_to='media', default='default.jpg') address = models.CharField(max_length=500, null=True, blank=True) billing_name = models.CharField(max_length=200, null=False, blank=False) account_num = models.IntegerField(default=1234) bank_name = models.CharField(max_length=50, null=False) branch_code = models.IntegerField(default=1234) def __str__(self): return "Profile of user {}".format(self.user.username) ... class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return "Profile of user{}".format(self.user.username) Here is my admin.py file from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import … -
Parse the JSON data in Word Docs using Python
I have on word document with tabular form and check list data, I need to fill the API JSON data into given specific position in word document. How can we do in python ? -
Django Form vs ReactJS SAP Form CSRF handling
I want to create a login form via using ReactJS. Previously when i learn Django form, all of it included a {% csrf_token %} to prevent attacker, I will get new csrf token everytime page is reloaded. Now I face problem on ReactJS form, how should I make a form with csrf token and achieve the same like Django form? Or there is other way to build form in ReactJS to prevent csrf attack. I assume Instagram is build using React, but I did not see any csrf token by inspecting the html. They store a same csrf token in the cookie without HTTPOnly. Can all form in ReactJS SAP using the same csrf_token? Why they store it in Cookie without httponly, I think the attacker can use the "document.cookie" to access the csrf token? All these bring a lot of confusion when I try to build a React Single Page Web Application. -
Django form populating dropdown from database values
I have a django form and I need to populate the dropdown field from database my form looks like prod_cat = forms.ModelChoiceField( queryset=ProductCategory.objects.values('prod_cat' ,'cat_desc').order_by('prod_cat' ,'cat_desc')) when I run render it to my html dropdown it looks like this, {'product_category':'Electronics','product':'Laptops'} I want to display only the values, like this Electronics Laptops -
Posting JSON to Django views with AJAX
I am trying to post a JSON object from my client side Javascript to my Django View. I receive a "500 (Internal Server Error)" When attempting to Post. Does this have to do with the CSRF token? And how can I get around this? My AJAX $.ajax({ type: 'POST', dataType: 'json', url: '/demo/saved/', data: {'data': JSON.stringify(finalSelection)}, success: function() { console.log("Success") } }); views.py def show(request): data = json.loads(request.POST.get('data', '')) context = { 'data': data } return render(request, 'bill/saved.html', context ) urls.py urlpatterns = [ path('bill/', views.bill_view, name = 'bill-view'), path('saved/', views.show, name = 'selected-view'), ] Appreciate any help! -
List of products from the given category
I'm just getting started and I have a problem. I want to get in SlugView a list of all products in the given category ('slug'). models.py class Category(models.Model): category_name = models.CharField(max_length=64) slug = models.CharField(max_length=64, unique=True) class Product(models.Model): name = models.CharField(max_length=128) description = models.TextField() price = models.FloatField() vat = models.FloatField(choices=VAT) stock = models.IntegerField() categories = models.ManyToManyField(Category) @property def name(self): return "Nazwa: {}, cena: {}".format(self.name, self.price) def __str__(self): return self.name views.py class SlugView(View): def get(self, request, slug): category = Category.objects.filter(slug=slug) return render(request,'exercises/slug.html', {'products': products}) urls.py re_path(r'categories/(?P<slug>\w+)', SlugView.as_view(), name = "slug") -
how to replace #text too a actual hastag?
i have a post create in django.. when a user type a text and hit submit it show on the html page. now i want if a user type some text with Hash it will show a hashtaglink in the html replacing the #sometext. i was working on that and i got a Uncaught SyntaxError: Unexpected token ',' my base.html: <script type="text/javascript"> $(document).ready(function() { $('.reply-btn').click(function() { $(this).parent().parent().next('.replied-comments').fadeToggle() }); }); $(document).ready(function() { function updateHashLinks(){ $("p").each(function(data){ var hashtagRegex = /(^|\s)#([\w\d-]+)/g var newText = $(this).html().replace(hashtagRegex, "$1<a href='/tags/$2/'>#$2</a>") $(this).html(newText) }); }, }); </script> -
Stream video using StreamingHttpResponse in HTML Template in Django
I used this solution https://stackoverflow.com/a/41289535/10772393 to stream video and it works perfectly fine. However, I am unable to figure out how to use it with an HTML template. I tried returning to the response to the HTML template but that doesn't work. I checked out this solution too Django StreamingHttpResponse into a Template however it is for live-streaming and outdated -
Setting a variable in session - Django Middleware
I have a custom middleware where I set request.session['user_image']= model_instance.image_field.url and I use this session variable in all the templates to display profile pictures in all the pages like this, Previously, I was using some external url as src attribute in image tag like this, src="http://url/media/users//fileName=user_userimage_20200102061417.jpg&viewOnly=true" . Now after changing it to the media url now, the image is not rendered in any of the pages. Can anyone help to get a better approach? -
Django Shell API KeyError
I am importing models in django shell API but i get the below error. Here is how it occurs: python manage.py shell from .models import Device I get: KeyError: "'__name__' not in globals"