Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: no such table: django_session
Premise: I'm a starter[Plz be kind and patient] When i try to run commands in the terminal like: python manage.py makemigrations audioma_manager or python manage.py runserver or python manage.py migrate or python manage.py --run-syncdb where audioma_manager is the name of my project I tried also with the name of my app I get this excetion code, I searched lots on the net but any kind of solution works with my problem: Traceback (most recent call last): File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: django_session The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\39371\AudioManVenv\lib\site-packages\django\core\checks\urls.py", line 13, … -
Dajngo forms placeholder and mask: data correctly saved in database but wrongly displayed at screen
I have an issue with formatting floatfield in Django. I set placehodler and data-mask: 000.0 When I enter data infields, it is correctly save in database but when I display form, it is wrongly displayed. For example, I enter '078.1' for weight. 78.1 is saved in database but when I open form, 781 is displayed. It seeems that 'missing' 0 at the beggining of floatnumber make it slice in the left and I lost comma models.py inc_poi = models.FloatField('Poids (kg)', null=True, blank=True) forms.py self.fields['inc_poi'] = forms.FloatField(label = 'Poids (kg)',widget=forms.TextInput(attrs={'placeholder': '000.0','data-mask':'000.0'}),required=False,disabled=DISABLED) -
Am following tutorials on Build powerful and reliable Python web applications from scratch by Antonio. But am stuck at Registering the image model [closed]
Even after i use the right password I still get that error -
Displaying all foreign keys a links
Is it possible to configure Django admin, so all foreign keys be displayed in the list view as links? Clicking on such a link should open the view for the related object. The closest I could find is list_display_links, which is actually unrelated, because it links to the current object... -
Enable editing a field in Django admin's list view
Consider a model that stores application forms. I would like to use Django admin to quickly view applications and change their status. I would like to be able to change the status of an application right in the view listing all the applications without having to open each application for editing. So, is it possible to make a field editable right in the admin list view? -
How to return sum according to date range in django?
It'd be really nice if someone could help me with this. I've stuck here. I'm able to do this manually but how to do according to user input. Payment.objects.filter(created_by=42, mode='cash', created_at__range=["2021-11-01", "2021-11-04"]).aggregate(Sum('amount')) Here created_by and date_range I'm sending in url like this : http://127.0.0.1:8000/api/v1/registration/?created_by=42&start_date=2021-06-06&end_date=2021-11-18 so the id created by and date_range will always change. And according to change the sum will return. My Model : class Payment(TimestampedModel): customer_visit = models.ForeignKey( CustomerVisit, on_delete=models.CASCADE, null=True, related_name="customer_payments" ) mode = models.CharField(choices=PAYMENTCHOICES, max_length=25) amount = models.FloatField() ref_no = models.TextField(null=True) bank = models.ForeignKey( "BankDetails", on_delete=models.CASCADE, null=True, related_name="payment_bank" ) is_settlement = models.BooleanField(default=False) created_by = models.ForeignKey("Employee", on_delete=models.DO_NOTHING, null=True,related_name='payment_created_by') updated_by = models.ForeignKey("Employee", on_delete=models.DO_NOTHING, null=True,related_name='payment_updated_by') My View : class UserWiseCollectionView(ListAPIView): permission_classes = [ IsAuthenticated, ] pagination_class = CustomPagination model = CustomerVisit serializer_class = UserWiseCollectionSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['created_by'] def get_queryset(self): start_date = self.request.query_params.get("start_date") end_date = self.request.query_params.get("end_date") emp_id = self.request.query_params.get("emp_id") items = self.model.objects.all() if start_date and end_date: items = items.filter( created_at__range=[start_date, end_date] ) if emp_id is not None: items = items.filter(phelebotomist_id = emp_id) return items -
Django: Load JSON into Bootstrap table with AJAX function + Missing Data
I want to create a simple application that can discover data from a database (a live program) with Django. One of the features is to display the list of tables. A response API that contains the list of table names from a database has been created: { "message": "success", "results": [ { "schema": "public", "table": "actor" }, { "schema": "public", "table": "actor_info" }, { "schema": "public", "table": "customer_list" }, { "schema": "public", "table": "film_list" }, .... ] } Then, I want to display the data (from API) in a bootstrap table by creating an AJAX function. This is my HTML file (full code is here): ... <div class="table-responsive"> <table class="table table-sm" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Schema</th> <th>Table Name</th> </tr></thead> <tbody id="divBody"></tbody> </table> </div> ... This is my AJAX function (Currently, I used the GET method. I want to change into POST method later): <script> $(document).ready(function () { BindTables(); }); function BindTables(){ $.ajax({ type:"GET", dataType: "JSON", url: "http://127.0.0.1:8000/api/v1/table/", success: function(data){ console.log("It's success"); console.log(data.results) var structureDiv = ""; for (let i=0; i < data['results'].length; i++){ structureDiv += "<tr>" + "<td>" + data['results'][i].schema + "</td>" + "<td>" + data['results'][i].table + "</td>" + "</tr>" } $("#divBody").html(structureDiv); } }); } </script> Currently, I can … -
object of type 'map' has no len()
I tried run my docker image for my django project and I have got a error. I research on google but could not any solution. Can anybody help me please! Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/code/Eventful-main/eventful/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
How can I upload images to a specific user in a self-created user table in Django?
I get an MultiValueDictKeyError with this code: I created 2 models one for the users and one for the photos. When a user is logged in, the user must upload a photo in the upload.html. The relationship between the user and photos models is one-to-many. I am strugling to upload the image, because of the foreign key value that must be retrieved from the loggin.html to the gallery.html then to the upload.html. My models: from django.db import models import os from django.contrib.auth.models import User class users(models.Model): username = models.CharField(max_length=20) email = models.EmailField() password = models.CharField(max_length=105) def __str__(self): return [self.username, self.email, self.password] def filepath(request, filename): return os.path.join('uploads/', filename) class photos(models.Model): user = models.ForeignKey(users, on_delete=models.CASCADE) title = models.CharField(max_length=20) description = models.CharField(max_length=100, null=True) location = models.CharField(max_length=50, null=True) image = models.ImageField(upload_to="media/") def __str__(self): return [self.user_id, self.title, self.description, self.location, self.image] My urls: from django.urls import path from . import views urlpatterns = [ path("index/", views.index, name="index"), path('', views.login, name="login"), path('login/', views.login, name="login"), path('test/', views.test, name="test"), path('register/', views.register, name="register"), path('gallery/', views.gallery, name="gallery"), path('upload/<int:user_id>/', views.upload, name="upload"), ] My views: from django.contrib.auth.decorators import login_required from django.db import transaction from django.shortcuts import render from main.models import users from main.models import photos from passlib.hash import sha256_crypt from django.http import HttpResponse … -
django-q multple cron expression for a single job
Is there a way to use multiple cron expression for a single job in Django-Q. I want a schedule a job for different day of different month. want to combine this- At 11:00 on day-of-month 10, 20, and 30 in January and every month from March through December-- 0 11 10,20 1,2,4-12 * At 11:00 on day-of-month 10, 20, and 28 in February.-- 0 11 10,20,28 2 * -
how to show message(Answer must be equal to the choices) and i want to remain on the same page, anyone?
This is my Add Question class #views.py class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) answer = request.POST['answer'] if answer == request.POST['option1'] or answer == request.POST['option2'] or answer == request.POST['option3'] or answer == request.POST['option4']: forms.save() return redirect(reverse('home')) else: print('invalid answer') return redirect(reverse('AddQuestion')) def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) -
Django Queryset : Left outer join multiple tables, group by different column that has same value?
I have following model sturcture : Model A : id misc id misc 1 something 2 randomstuff Model B : id : Foreign Key A.id date amount id date amount 1 2021-11-15 10 1 2021-11-16 15 2 2021-11-16 20 Model C : id : Foreign Key A.id date amount id date amount 1 2021-11-15 1 2 2021-11-16 2 2 2021-11-16 3 So I want to make a queryset where I can Left join three tables, where B and C has a "date" column which, relationwise, not related, but in practice are exact same column. So I want to make an aggregated table, and my desired output is : id date A.amount B.amount 1 2021-11-15 10 1 1 2021-11-16 15 0 2 2021-11-15 20 2 2 2021-11-16 0 3 which basically means joining B and C by id and date. Any regular join attempts obviously gave me like 6+ rows instead (since B.date and C.date is a completely different column in theory and they just outer join for each combination), so I was looking for a way to join two relations with multiple "ON"s. I tried FilteredRelation, as following : res = (qs .annotate(BB=FilteredRelation('B, )) .annotate(CC=FilteredRelation('C',condition=Q(C__date=F('B__date')) )) .values("id","BB__amount","CC__amount") ) print (res.query) … -
How to query Django PostGIS / Postgres DB with the map / Leaflet boundary box view?
Results from query made with other fields are populated on Leaflet: var myMap = L.map("mapid", {zoomControl: false}); L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {maxZoom: 18 }).addTo(myMap); myMap.setView([-34, 151], 12); var markers = [ {% for journal in queryset %} L.marker([{{ journal.latitude }}, {{ journal.longitude }}]), {% endfor %} ] var group = L.featureGroup(markers).addTo(myMap); I now want the results populated by where the user places Leaflet's boundary box, but I'm bewildered on how to do that. I've got GDAL installed, have converted the long / lat cols to a spatial col in Postgis with ADD COLUMN geom geometry(Point, 4326) GENERATED ALWAYS AS (ST_SetSRID(ST_MakePoint("longitude", "latitude"), 4326)) STORED, added geom = models.PointField(blank=True, null=True) to models.py, but am lost on where to go from here. Someone has suggested I incorporate this into a view but I don't know how to make sense of it: from django.core.serializers import serialize entries = Entry.objects.all() data = serialize('geojson', entries, geometry_field='point', fields=('id', 'name',)) This seems the most authoritative tutorial on the topic but I'm totally lost when he gets to views and talks of a generic class based view / list views / Django Rest Framework. Is there a dumbed down explanation somewhere? I feel like an idiot. Unsure if relevant but the table … -
Is there a way to show login error in Django?
I have a custom login page for my web. Upon keying the right account details, I can log in to my web. But if I key in wrong account details, it just refreshes the pages with the username and password 's textbox empty. Is there some way to show something like 'Username or Password is wrong' as a error or message? Within the login.html I have the following {% if messages %} {%for message in messages%} <div class ="alert alert-success" role="alert"> {{message}} </div> {%endfor%} {%endif%} {% for field in form %} {% if field.errors %} {% for error in field.errors %} <div class="alert alert-danger" role="alert"> <div class="d-flex flex-row"> <div class="align-middle pr-2"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-circle-fill" viewBox="0 0 16 16"> <path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM5.354 4.646a.5.5 0 1 0-.708.708L7.293 8l-2.647 2.646a.5.5 0 0 0 .708.708L8 8.707l2.646 2.647a.5.5 0 0 0 .708-.708L8.707 8l2.647-2.646a.5.5 0 0 0-.708-.708L8 7.293 5.354 4.646z" /> </svg> </div> <div class="align-middle"><b>{{field.label}}</b> - {{error}}</div> </div> </div> {% endfor %} {% endif %} {% endfor %} The following does not seem to do anything if the username or password is incorrect. -
Page not found (404) The current path, api/posts/1, didn’t match any of these
I'm trying to create an api through Django rest framework and using NextJS for the frontend. I can get all the post data without any error. but when i try to get data for one post it gives me and error saying "Page not found (404) The current path, api/posts/1, didn’t match any of these." Here all of the files in my api folder api/serilizer.py: [1]: https://i.stack.imgur.com/e132y.png api/urls.py: [2]: https://i.stack.imgur.com/07jTJ.png api/views.py and project/urls.py [3]: https://i.stack.imgur.com/s0g8t.png [4]: https://i.stack.imgur.com/twh9S.png Please tell me what is wrong. Thanks -
Creating choices field based on another modelForms entries
I currently have 2 models, 1 for customers and 1 for JobCards I would like to automatically add the "customers" data into the "JobCards" entries with a choices field. However, I am getting the following error with my code: TypeError: 'newCustomersClass' object is not subscribable Please see the following code class newCustomersClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) customerClass = newCustomersClass.objects.all() customers = [] for row in customerClass: rdict = {} rdict.customerName = row[0] customers.append(rdict) class jobCardsClass(models.Model): customerName = models.CharField(choices=customers ,max_length=100 , blank=False , default=1) Is it possible to append an array like this from a model form? Otherwise, what would be a better way to do so? -
How can I use pdf.js to display the first page of every user-uploaded pdf file as a preview in Django?
Up to now i have successfully display the first page preview for one pdf file but it doesn't work for remaining others. models.py import uuid from django.db import models class PdfUploader(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) docfile = models.FileField(upload_to='documents/%Y/%m/%d') uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'pdf_uploader' ordering = ['-uploaded_at'] @property def filename(self): return self.docfile.name.split("/")[4].replace('_',' ').replace('-',' ') views.py class PdfUploadView(CreateView): def get(self, request, *args, **kwargs): context = {'form': PdfUploadForm()} return render(request, 'partials/pdf_upload_form.htm', context) def post(self, request, *args, **kwargs): form = PdfUploadForm(request.POST, request.FILES) files = request.FILES.getlist('docfile') if form.is_valid(): for f in files: file_instance = PdfUploader(docfile=f) file_instance.save() return HttpResponseRedirect(reverse_lazy('pdf-list')) return render(request, 'partials/pdf_upload_form.htm', {'form': form}) pdf_upload_form.htm {% block "content" %} <div role="main" class="main"> <section class="section section-default pt-5 m-0"> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> </div> </section> </div> {% endblock %} pdf_lists.htm By following official official django docs, I am passing a context variable as JSON to the pdf.js. {% for obj in pdfs %} <tr> <td> {{ forloop.counter }} </td> <td> <a href="{{ obj.docfile.url }}" target="_blank" rel="noopener noreferrer">{{obj.filename}}</a> </td> <td> {{ obj.uploaded_at|date:"d-M-Y" }} </td> <td> <a href="{{obj.docfile.url}}" target="_blank" rel="noopener noreferrer"> <canvas id="the-canvas" style="height:250px;"> </canvas> {{obj.docfile.url|json_script:'mydata'}} </a> </td> </tr> {% endfor %} pdf.js Now I'm reading … -
Using a postgres composite field containing a geography type for django ORM usage
So i have a composite field that i want to use in my django models using postgres as the DB. CREATE TYPE address_verbose AS ( contact_person_name string_not_null, mobile string_no_spaces, mobile_cc string_no_spaces, email email_with_check, address text, city text, state text, country text, pincode string_no_spaces, location geography ); The string_not_null, string_no_spaces and email_with_check are just domains i have created for validation. Everything works fantastically if i use SQL, but the thing is want to use this field in a django models and i want to use Django ORM for at least creating, updating and deleting objects containing this field. So after some google search i was able to come up with a custom model field. from typing import Optional from django.contrib.gis.geos import Point from django.db import connection from django.db import models from psycopg2.extensions import register_adapter, adapt, AsIs from psycopg2.extras import register_composite address_verbose = register_composite( 'address_verbose', connection.cursor().cursor, globally=True ).type def address_verbose_adapter(value): return AsIs("(%s, %s, %s, %s, %s, %s, %s, %s, %s, ST_GeomFromText('POINT(%s %s)', 4326))::address_verbose" % ( adapt(value.contact_person_name).getquoted().decode('utf-8'), adapt(value.mobile).getquoted().decode('utf-8'), adapt(value.mobile_cc).getquoted().decode('utf-8'), adapt(value.email).getquoted().decode('utf-8'), adapt(value.address).getquoted().decode('utf-8'), adapt(value.city).getquoted().decode('utf-8'), adapt(value.state).getquoted().decode('utf-8'), adapt(value.country).getquoted().decode('utf-8'), adapt(value.pincode).getquoted().decode('utf-8'), adapt(value.location).getquoted().decode('utf-8'), )) register_adapter(address_verbose, address_verbose_adapter) class AddressVerbose: def __init__(self, contact_person_name: str, mobile: str, mobile_cc: str, email: str, address: str, city: str, state: str, country: str, pincode: str, location: Optional[Point] … -
Encrypting a django field (not a password)
I have an ecommerce website made with django and I want to store details of orders. The fields would have id, thing bought, quantity, total price, etc. Right now I only have them stored as plaintext so I want to make it more secure. Hashing isn't an option because I want to be able to read the data. I though about encryption, but is there any other way? If there isn't I have a few questions, How do I safely encrypt and decrypt the data Where and how do I store the encryption key Will there be just 1 master key? Any help is appreciated! -
How to setup Postman to handle APIs from remote server
I have my django server running in a ssh client (ubuntu) but I want to test the api's in the local window machine. How could I achieve that? -
How to throttle redis/celery tasks for a django web site?
I have a django v3.0.2 site (python v3.6.9) where I upload an image, process the image, and then display it on a web site. By process the image, I create different sizes of the the one image, find and identify faces, ocr any text and translate it if needed, use several different algorithms to calculate how similar each image to the others, and other image processing algorithms. I use celery v4.3.0 and redis v4.0.9 to do all the calculations in the background in different celery tasks. The issue I am having is that when I try to upload and process more than ~4 images in a loop, I run out of memory and the calculations start to throw exceptions. By run out of memory, my 5 GB of swap and 16 GB of ram are all used up and chrome even crashes. In my database, I keep a log of the progress of each task and whether it completes successfully or not. I can see many errors and many tasks not started. If I put a time.sleep(10) in the loop that uploads the images and right after the celery workers are launched for each image, I can upload 60+ images … -
how to save bootstrap modal form upon submit in django?
I'm new to ajax and I need help. I was able to open the modal when I clicked the Add grade, now my problem is how to save the form to the database using modal? that error page will show if I hit the save changes in modal form. views.py class GradeUpdateView(LoginRequiredMixin, UpdateView): model = Subject template_name = 'teacher/modal.html' # fields = ['grade'] # success_url = '/' form_class = UpdateGradeForm def get_success_url(self): subject = self.object.subject_name year = self.object.year_taken return reverse_lazy('student-list', kwargs={"subject_name_id": subject.id, "year_taken": year}) modal.html <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalCenterTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" id="grade-form"> <div class="modal-body"> {% csrf_token %} {{ form.as_p }} {% comment %} <input type="submit" class="btn btn-sm btn-block btn-primary" value="Save"> {% endcomment %} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" data-form-url="" class="btn btn-primary" id="save-form">Save changes</button> </div> </div> </form> </div> </div> </div> main.js var modalDiv = $("#modal-div"); $(".open-modal").on("click", function () { $.ajax({ type: 'GET', url: $(this).attr("data-url"), success: function (data) { modalDiv.html(data); $("#exampleModalCenter").modal(); } }); }); -
Automatically taking picture when face detected using Django?
I successfully used StreamingHttpResponse to open the webcam on a template and detect face. But I don't know how to automatically take picture of the detected face and display it on the template. -
Implementing Pagination with Django-Filter
I am looking to implement Pagination with Django-Filter's function based view. I currently have the search function working, but have not been able to find documentation online on how to implement pagination with Django-filter; haven't been able to get it working with references i've found online. What I have so far: views.py from django.shortcuts import render from .models import Stock from .filters import StockFilter def home(request): return render(request, 'stockwatcher/home.html', {'title': 'Home'}) def stock_search(request): f = StockFilter(request.GET, queryset=Stock.objects.all()) return render(request, 'stockwatcher/search_results.html', {'filter': f}) filters.py import django_filters from .models import * class StockFilter(django_filters.FilterSet): senator = django_filters.CharFilter(field_name='senator' ,lookup_expr='icontains') ticker = django_filters.CharFilter(field_name='ticker', lookup_expr='iexact') class Meta: model = Stock fields = [ 'senator', 'ticker' ] exclude = [ 'asset_description', 'asset_type', 'amount', 'type', 'transaction_date', ] urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.home, name="stockwatcher-home"), path('stocks/', views.stock_search, name="stockwatcher-stocks"), path('about/', views.about, name="stockwatcher-about")] search_results.html {% extends "stockwatcher/base.html" %} {% block content %} {% load widget_tweaks %} <div class="container"> <div class="row" style="padding: 50px;"> <form method="get"> {{ filter.form.as_p }} <input type="submit" /> </form> </div> <div class="row"> {% for stock in filter.qs %} <div class="col-4"> <div class="card text-white bg-info mb-3" style="max-width: 18rem;"> <div class="card-header">{{stock.transaction_date}}</div> <div class="card-body"> <h5 class="card-title" style="color: white"> {{stock.ticker}} </h5> <p class="card-text">{{stock.senator}} - … -
Does anyone know why base appears instead of virtualvenv? Pycharm
Does anyone know why base appears instead of virtualvenv? How can I reactivate it? I am with Pycharm on Windows I was working well with venv and suddenly at night he changed it for base