Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OpenCv can't open camera by index after deployment
I'm Using OpenCv for detecting the face. I'm fetching image from the video. When I'm running the code on my local machine to capture video, it's working fine. But when running the same code after deployment on Heroku it's not working. Below is the error- [ WARN:0] global /tmp/pip-req-build-dzetuct2/opencv/modules/videoio/src/cap_v4l.cpp (890) open VIDEOIO(V4L2:/dev/video1): can't open camera by index Below is the code- Views.py class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(1) camera_backends = cv2.videoio_registry.getCameraBackends() print("ca",camera_backends) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() I tried using index value 1 and 2 both but did not work for me. Someone Please help. Thanks in advance. -
Additional auth tables when extending Djangos AbstractUser
I am new to Django and discovered something I do not quite understand: I extended the default user class of django auth with a custom field to look like this: class User(AbstractUser): business_entity = models.ForeignKey('BusinessEntity', on_delete=models.PROTECT) In the settings file, I also added the needed AUTH_USER_MODEL = 'core.User' since my new user model is located in the core app. Works fine so far. After applying all migrations (even after wiping the database and reapplying), I, however, am left with a few additional tables that I did not want to create and that seem not to be used by Django's auth app: Tables created after migration As you can see there are from the auth app: auth_group, auth_group_permissions and auth_permissions as well as from core app: core_user_groups, core_user_user_permissions. I searched quite a while - maybe with the wrong keywords? - but I am not able to figure out if I need all those tables and - especially - what the additional core tables are used for. Can you shed some light on this? Thank you very much! -
Populate Data in Database Using YAML File through Fixtures in Django
I'm trying to populate the data in the database for the Employee Model Also, I'm not going to use Foreign Key ID's as given below Example 1: - model: employee.employee pk: 1 fields: user: 1 manager: NULL department: 1 job_level: 5 created_at: '2021-06-03' updated_at: '2021-06-03' Instead, I'm going to Use Unique values of the respective Model as given below Example 2: - model: employee.employee pk: 1 fields: user: [manager.finance] manager: NULL department: [Finance] job_level: [MNGR] created_at: '2021-06-03' updated_at: '2021-06-03' models.py File from django.db import models from django.conf import settings from django.db.models import Q class TimestampedModel(models.Model): created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) class Meta: abstract = True class DepartmentManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class Department(TimestampedModel): name = models.CharField(max_length=128, unique=True) objects = DepartmentManager() class Meta: db_table = 'tc_departments' def __str__(self): return f'{self.name}' class JobLevelManager(models.Manager): def get_by_natural_key(self, handle): return self.get(handle=handle) class JobLevel(models.Model): handle = models.CharField(max_length=32, unique=True) display_name = models.CharField(max_length=64, null=True, blank=True) objects = JobLevelManager() class Meta: db_table = 'tc_job_levels' def __str__(self): return f'{self.handle} and {self.display_name}' class EmployeeManager(models.Manager): def get_by_natural_key(self, user): return self.get(user=user) class Employee(TimestampedModel): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) manager = models.ForeignKey('self', on_delete=models.CASCADE, limit_choices_to={'manager__isnull': True}, null=True, blank=True) department = models.ForeignKey(Department, on_delete=models.CASCADE) job_level = models.ForeignKey(JobLevel, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='photos/%Y/%m/%d', max_length=128, null=True, blank=True) objects = … -
Problem while rendering time from django datetime field in html input tag
I want to render datetime fields time value in html time field but when I pass the value to it , it does not show but in the value only it comes. here is my template <div class="form-group col-md-6"> <label for="message-text" class="col-form-label">Deadline Time:</label> <input required type="time" name="deadlinetime" value="{{list.deadline.time}}" class="form-control" /> </div> Please help me.. -
can't return back to question detail page after editing answer in django
This is the code of my update answer def Update_Answer(request, id): ans = Answer.objects.get(pk=id) quest = Question.objects.get(pk=id) answerform = AnswerForm(request.POST or None,instance=ans) if answerform.is_valid(): answerform.save() messages.success(request, 'Answer has been submitted.') return redirect('detail', id) return render(request, 'update_answer.html', { 'form': answerform }) Here when i select an answer to be edited, it generates a url with answer id. But after i edit my answer, i automatically want to return back to question id . -
How can neglect the value which exist in db django
I am try to show only those saloon when is still not link to any user, but my query set return those saloon which is already linked with user Model.py class SaloonRegister(models.Model): saloon_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() is_active = models.BooleanField(default=False) class SignUp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) contact_no = models.BigIntegerField() view.py class AllSaloon(TemplateView): template_name = 'allSaloon.html' def get(self, request, *args, **kwargs): saloon = SignUp.objects.filter(saloon_id__isnull=False) return render(request, self.template_name, {'saloon': saloon}) -
sort array of nested objects by date Django
I am newbie to django, I have table which store the comments, but each comment can have child comments and child comments can have another child comments. I am trying to sort it based on most recent date but only the first layer of comments are sorting. queryset = File.objects.filter(comment__icontains=comment).order_by('comment_created') I am attaching a sample json tree for better understanding -
Django custom dropdown depending on field type
I have the models: class DeepLink(models.Model): class DeepLinkType(models.TextChoices): TRACING = ('Tracing', 'Tracing') BUTTON = ('Button', 'Button') MODAL = ('Modal', 'Modal') id = models.UUIDField(primary_key=True, default=uuid4) type = models.CharField(max_length=7, choices=DeepLinkType.choices, blank=False) uri = models.UUIDField(blank=False, default=uuid4) class Meta: db_table = 'deeplink' class Button(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) text = models.CharField(max_length=500, blank=False) link = models.CharField(max_length=250, blank=False) image = models.CharField(max_length=250, blank=True) class Meta: db_table = 'button' class Modal(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) image = models.CharField(max_length=250, blank=True) header = models.CharField(max_length=250, blank=True) body = models.CharField(max_length=250, blank=True) class Meta: db_table = 'modal' class Tracing(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) external = models.BooleanField(blank=True, default=False) external_link = models.CharField(max_length=250, blank=True) class Meta: db_table = 'tracing' I need to have a dropdown for the field uri in the Django Admin depending on type have chosen. For example, if we choose type as Button, the uri field should be a dropdown for all possible buttons etc. Obviously I can't declare uri as foreign key because it can refer to 3 tables. Hence it's just a text field in the admin now. How is it possible to make such dynamic dropdown in Django Admin? -
Django Empty Date Field With SQLITE
In my models under the class I have this column in my rows that once a client accepts a quote it will be filled in so it can be empty. quote_accepted = models.DateField(blank=True, null=True) I want to be able to pull all lines where the quote_accepted field is not set. Some of the Ways I Tried: "awaiting_quote": Order.objects.filter(quote_accepted='') "awaiting_quote": Order.objects.filter(quote_accepted=' ') "awaiting_quote": Order.objects.filter(quote_accepted='True') "awaiting_quote": Order.objects.filter(quote_accepted='TRUE') "awaiting_quote": Order.objects.filter(quote_accepted='Null') "awaiting_quote": Order.objects.filter(quote_accepted='NULL') -
html divider border not properly including all subcontents
First time trying to make an HTML/CSS Django website, thank you for the patience. I'm working from a simple resume template and trying to fix an error I found from the start (template in question https://github.com/resume/resume.github.com/tree/47aba3b380459c07967b4f38c9e77fbe42be07a6). I have a section of my section of my website with the following visual error (https://imgur.com/a/GaIUXB4). The 1px thick section divider line is being placed below the headings rather than after the full content of the section. This is not an issue for other sections of the website, but the stacked, non line-by-line elements like these two sections have issues. The html section is <div class="yui-gf"> <div class="yui-u first"> <h2>Skills</h2> </div> <div class="yui-u"> <div class="talent"> <h2>Multi-System Design</h2> <p>Proven experience with robotic systems spanning mechanical, electrical, and software backgrounds.</p> </div> <div class="talent"> <h2>Interpersonal Reporting</h2> <p>Familiarity with reporting, documentation, and organization of technical design documents.</p> </div> <div class="talent"> <h2>Problem Based Solutions</h2> <p>Involvement with team based, problem driven projects that solve a question rather than a set task.</p> </div> </div><!--// .yui-u --> </div><!--// .yui-gf --> <div class="yui-gf"> <div class="yui-u first"> <h2>Technical</h2> </div> <div class="yui-u"> <ul class="talent"> <li>SolidWorks</li> <li>Autodesk Inventor</li> <li class="last">Autodesk Eagle</li> </ul> <ul class="talent"> <li>MATLAB</li> <li>Python 3</li> <li class="last">ROS</li> </ul> <ul class="talent"> <li>SimTK OpenSim</li> <li>SimTK SCONE</li> … -
How can I iterate through a Celery Chain in Django?
I'm using Celery 5.1.0 with Django 3.2.3 and have a Celery Chain set up. I wish to run this chain in a loop, but I need to ensure that the loop only starts again once the previous set of commands in the chain have completed. This is the Chain: def base_data_chain(user_email, store): chain = ( product_count.s(store=store) | get_data.s(store=store) | normalise.s() | merge.s() | send_task_email.s(user_email=user_email, store=store)) chain() What I need is somthing like this: for store in stores: base_data_chain(user_email=user_email, store=store) But I need the loop for each store not to begin until the previous store has been processed. Any help on the best way of achieving this would be appreciated. Thanks. -
SQLAlchemy equivalent for Django `__` subquerying
I'm pretty new to SQLAlchemy (specifically with Flask). I'd like to replicate a subquery that would look like this on Django: Blah3.objects.filter(id=1, blah2__blah1_id=1).exists() where the models look like: class Blah1(models.Model): ... class Blah2(models.Model): blah1 = models.ForeignKey(Blah1) class Blah3(models.Model): blah2 = models.ForeignKey(Blah2) So what would that nested subquery in SQLAlchemy look like? I already did: obj = Blah3.query.filter_by(id=1).one_or_none() assert obj.blah2.blah1_id == 1 But that requires more queries plus all I really need is do do an EXISTS subquery and really the entire thing should be an EXISTS. Any ideas how to jam pack all this into one query? Thanks! -
Can I use my own file extension for Django Templates and still include django.contrib.auth.urls?
I can easily just use html.djt as i wish, but only if i let the built-in class based views know which template i want to use. A custom extension allows me to configure my editor to recognize django templates, which helps with code formatting and highlighting etc. In this example i would need to reference a template using template_name: path( "login/", auth_views.LoginView.as_view(template_name="registration/login.html.djt"), name="login", ), It can be handy to include all the url authentication patterns like this: from django.urls import path, include # ... urlpatterns = [ # ... path('', include('django.contrib.auth.urls')), ] However is it still possible to use a custom file extensions for the templates if i include the built-in url patterns? -
How to do orm query for a post that has hit count generic field?
I have a blog that has hit count field. How should I order the posts with high hit count field? Here is my model: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') For some reason I am not seeing any posts. I get a blank list of posts. Here is my view:- def post_list(request): template_name = 'blog/posts.html' post_list2 = Post.objects.filter(status=1).order_by('-hit_count_generic__hits') for post in post_list2: post.like_status = post.number_of_likes() post.comments_status = post.comments.filter(active=True).count() return render(request, template_name, {'post_list': post_list2) <div class="container my-3" style="margin-top: 0rem!important;" > <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 " style="margin-top: 0rem!important;" > <h4> <span class="badge badge-primary" style="background-color: #b0981f;">Blog Posts for Category : {{category}} | {{ total_posts}} Post{{ total_posts|pluralize }}</span></h4> {% if post_list %} {% for post in post_list %} <div class="card text-left bg-light mb-3" style="margin-bottom: 20px;"> <div class="card-header">........ -
Validate form fields on server side without ajax - Django
I have a form which takes input from user which is actually a path in an input field. I need to validate the path and display an alert if it already exists. So far I have been validating on submit button click event by making an ajax call to the server side(django - python) and returning it as jsonresponse. Is there any other way to check the existence of mentioned path and display alert to user if exists in django framework? Appreciating help. Thanks in advance. -
django select records from multiple tables with same foreign key
I would like to execute a single query in Django which retrieves related data, by foreign key, in multiple tables. At present I have to run a query on each table e.g. (House, Furniture, People) using the House number as a filter. In SQL I can do this in one query like this: SELECT house.number, house.number_of_rooms, furniture.type, people.name FROM (house INNER JOIN furniture ON house.number = furniture.house_number) INNER JOIN people ON house.number = people.house_number WHERE (((house.number)="21")); Can this be done in Django? See example models below: class House(models.Model): number = models.CharField('House Number', max_length=10, blank=True, unique=True, primary_key=True) number_of_rooms = models.IntegerField(default=1, null=True) class Furniture(models.Model): house_number = models.ForeignKey(House, on_delete=models.CASCADE, null=True) type = models.CharField('Furniture Type', max_length=50) class People(models.Model): house_number = models.ForeignKey(House, on_delete=models.CASCADE, null=True) first_name = models.CharField('First Name', max_length=50) -
Add element in many to many field and preserve order
class Country(Models.Model): code = models.CharField(max_length=50) name = models.CharField(max_length=500) class Meta: unique_together = (('code', 'name'),) db_table = 'md_country' class UserSettings(models.Model): ... default_countries = models.ManyToManyField(Country, db_table='user_default_countries', related_name='default_countries') I have two models inside django models, what im trying is when i add Country models to default_countries i want to preserve order. Currently when i append manytomany field django automatically sort by Country name (alphabetical order) I have this code # iterate one by one to preserve fetching order country_models = [Country.objects.get(id=_id) for _id in request.data[default_countries]] user_settings.default_countries.clear() for c in country_models: user_settings.default_countries.add(c) After this when i inspect user_settings.default_countries i have ordered countries by name in alphabetical order. I want to preserve when adding element -
Django: Passing a continuous Outpout Variable to Html View
I am using Django for a local server. I need to pass a continuous variable from the views.py file to the HTML view with a click of a button. I made a simple code trying to do this but I didn't finally achieve it. I tried to use channels and WebSockets in the asynchronous environment of Django. I have a for loop into the views.py file for creating a value for the variable which I want to pass. Do I need to move this loop to the aswi.py file? My starting code is as follows: Index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Real-Time with Django</title> </head> <body> <form action="/start_button" method="GET"> <input class="button_start" type="submit" value="START" /> </form> {{text }} </body> </html> Views.py from django.shortcuts import render from random import randint def index(request): return render(request, 'index.html') def start_button(response): for i in range(5): return render(response, "index.html", {'text': randint(1, 100)}) Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path("start_button/", views.start_button) ] -
Translate Dockerfile from python-alpine to python-slim-buster (debian-based)
I am trying to improve the Dockerfile we use for deploying a Django-based app at work and first thing I would like to do is change the base image of python from alpine to slim-buster but I have to translate it to a debian-based image. I would like some suggestions on how I could translate it since I have zero to none experience with alpine. This is the original snippet from Docker. FROM python:3.8.6-alpine3.12 RUN apk update && \ apk add --virtual build-deps gcc g++ musl-dev && \ apk add postgresql-dev vim bash nginx supervisor curl && \ apk add libffi-dev && \ apk add --update npm && \ apk add git make cmake -
Chat message in Django-Channel not broadcasting
I am working with django-channels. I created a consumer to broadcast a message. The strange thing is that after opening 2 windows to see the broadcast, the below happens. The message is displayed on the last refreshed window (the number of message coincides with number of windows opened). But the message never gets to displayed on the other windows. channels==3.0.3 channels-redis==3.2.0 Django==3.2.3 Below is my consumer.py class EchoBroadcastConsumer(SyncConsumer): def websocket_connect(self, event): self.room_name = 'broadcast' self.send({ 'type': 'websocket.accept', }) async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) print(f'[{self.channel_name}] - You are connected!') def websocket_receive(self, event): print(f'[{self.channel_name}]- You are have received {event["text"]}') async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': event.get('text') } ) def websocket_message(self, event): print(f'[{self.channel_name}] - Message Sent {event["text"]}') self.send({ 'type': 'websocket.send', 'text': event.get('text') }) def websocket_disconnect(self, event): print(f'[{self.channel_name}] - You are have Disconnected') async_to_sync(self.channel_layer.group_discard)(self.room_name, self.channel_name) Below is my frontend (JS) const url = 'ws:127.0.0.1:8000/ws' + window.location.pathname; const ws = new WebSocket(url); ws.onopen = function(event){ console.log("Connection is Open"); } ws.onmessage = function(event){ console.log("Message is received"); const ul = document.getElementById('chat_list'); var li = document.createElement('li'); li.append(document.createTextNode(event.data)); ul.append(li); // var data = JSON.parse(event.data) //li.append(document.createTextNode( // '['+ data.username+ ']:' + data.text //)); ul.append(li); } ws.onclose = function(event){ console.log("Connection is Closed"); } ws.onerror = function(event){ console.log("Something went wrong"); } const message_form = document.getElementById('message_form'); … -
Getting Error While Creating Super user in my Django project
I AM USING PHPMYADMIN FOR DATABASE enter image description here -
Django 'NoneType' object is not callable
I try to use BeautifulSoup to clean html from class, id etc. and then save them. Clear html works fine, but when I try save this, I get: File "<console>", line 1, in <module> File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 754, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 792, in save_base force_update, using, update_fields, File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 873, in _save_table forced_update) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 926, in _do_update return filtered._update(values) > 0 File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 799, in _update query.add_update_fields(values) File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/subqueries.py", line 108, in add_update_fields val = val.resolve_expression(self, allow_joins=False, for_save=True) TypeError: 'NoneType' object is not callable ``` My code: @shared_task def clean_article_html(article_id): try: article = Article.objects.get(id=article_id) except ObjectDoesNotExist: pass else: html = BeautifulSoup(article.body, 'html.parser') for tag in html(): for attribute in ['class', 'id', 'name', 'style']: del tag[attribute] article.text = html article.save() Maybe someone have idea what wrong with this code. -
Netbox Plugin Development and Instalation
I am new to Netbox Plugin Development, Please guide me from scratch to create simple blank plugin. I am using Windows system with docker running in it. and Netbox is running in that Docker. I have searched a lot on Google but not found anything on it. Here is one question but i am not getting anything from it. Here is another example but it is also not working for me. Thank You -
Django context processor throw error on redirect
I'm using the following context processor to pass context to all my pages, except when the user is not logged in which case it takes him to the login page : from django.conf import settings from .models import foo from django.shortcuts import redirect def globalVar(request): if not request.session.get('user_id') is None: return {"foo": foo} else: return redirect('login') But the redirect causes an exception for which i didn't find a fix : ValueError: dictionary update sequence element #0 has length 0; 2 is required Am i not looking in the right place, or is there a way to replace redirect by something else ? -
how to add links to sticky navigation bar
I'm developing blog with django.And I add sticky navigation bar to my web site but after that I can't add the url to different menu like "Home","News","Contact".Because there already a "href" tag inside anchor tag.by the way I want load "home.html","News.html","contact.html" pages when I clik "Home","News","Contact".Anyway here is my code. <!DOCTYPE html> <html> <head> <title>Dinindu Theekshana</title> <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Roboto", sans-serif; font-size: 17px; background-color: #fdfdfd; } .shadow{ box-shadow: 0 4px 2px -2px rgba(0,0,0,0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background:#3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar { overflow: hidden; background-color: #333; color: #333; z-index: 9999999; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #294bc5; color: white; } .content { padding: 16px; padding-top: 50px; } .sticky { position: fixed; top: 0; left: 0; width: 100%; } .sticky + .content { padding-top: 60px; } </style> <!-- Nav bar --> <nav class="navbar …