Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with Unicorn losing thread local storage during requst
I've set up a request-scope cache using middleware and tried to set it to be available from anywhere using threading.local() variable. However, sometimes long requests processes drop with the following error: File "label.py", line 29, in get_from_request_cache label = cache.labels[url] AttributeError: '_thread._local' object has no attribute 'labels' However, some of the items get processed correctly, and they all depend on existence of that cache. The cache object is initialized once and is cleared at the end of the request using the following middleware: request_cache.py import threading _request_cache = threading.local() def get_request_cache(): return _request_cache class RequestCacheMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): global _request_cache response = self.get_response(request) _request_cache.__dict__.clear() return response def process_exception(self, request, exception): _request_cache.__dict__.clear() return None And the only code that accesses the cache object directly is this part: label.py import django.db.models from request_cache import get_request_cache from base import Model class Label(Model): **model fields** @staticmethod def create_for_request_cache(urls): cache = get_request_cache() urls = set(urls) if not hasattr(cache, 'labels'): cache.labels = {} new_urls = urls.symmetric_difference(set(cache.labels.keys())) entries = [Label(url=url) for url in new_urls] if entries: Label.objects.bulk_create(entries) for entry in entries: cache.labels[entry.url] = entry @staticmethod def get_from_request_cache(url): cache = get_request_cache() label = cache.labels[url] return label The request that crashes is split … -
In Wagtail is there a way to have a listing/index page list sub pages in a manually specified order without the InlinePanel listing every field?
I want to have a page (/blog/) that lists sub-pages. But I don't want to order them by most recent or anything like that. I want to order them in a manually specified way. I'd love to use an Orderable on the sub-pages, but the only way I've been able to get that to work is if I use an InlinePanel. The problem with an InlinePanel, is then Wagtail will show each page inlined with every field, and each page can be really long. Is there a way to use InlinePanel, but only show the title of each page vs. every single field? Or is there a better way to do this in Wagtail? -
How to empty a many to many field in django
I would like to empty all things within the following many to many field(weekday_with_class): all_existing_class.weekday_with_class = None Here is the models.py: weekday_with_class = models.ManyToManyField('Weekday', blank=True, related_name='weekday_with_class') However, if I execute the above code, I get this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use weekday_with_class.set() instead. How is it possible to basically make my weekday_with_class empty for an instance? Thank you, and please leave a comment if you need any more information. -
Is there such a thing as a conditional "ON DELETE CASCADE" in Django?
Is there a simple way, using on_delete, to delete the object containing a ForeignKey when that ForeignKey is deleted (like models.CASCADE would normally do) but just the ForeignKey relationship to None if some condition is met (like models.SET_NULL would normally do). Here is some code: class SomeThing(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="things", on_delete=models.CONDITIONAL_CASCADE, # obviously this is wrong ) is_private = models.BooleanField(default=False) >>> user = User(username="bob").save() >>> public_thing = SomeThing(is_private=False) >>> private_thing = SomeThing(is_private=True) >>> user.things.add(public_thing) >>> user.things.add(private_thing) >>> user.delete() When user is deleted I would like private_thing to be deleted along w/ user, but public_thing to not be deleted and for public_thing.user to be set to None. Thanks. -
Error while using signals, Django doesnt see a inbuild User model app_label
I'm learning django signals and when I'm trying to use simple one which creates Profile directly after new User is created( by default django User model) and whenever I try to runserver, I get this error: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. HOWEVER: django.contrib.contenttypes is in INSTALLED_APPS I'm newbie and I'm stuck..... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'bootstrapform', 'basic', ] # urls """Filmweb URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.contrib.auth import views as auth_views from basic.views import Main, ActorsListView, ActorModifyView, ActorCreateView, \ ActorDeleteView, Films, FilmCreateView, FilmModifyView, FilmDeleteView, Register, RateIt, FilmDetails, Profile, \ RolesView, RoleModifyView, RestFilmView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ … -
Import recipe from a website using Django REST Framework and React Native
So I am working on a meal planning mobile application and have seemed to hit a roadblock. Apparently, the client wants a feature where if a user clicks on the "Import Recipe" Button in the application, A browser should open which would allow the user to surf the internet and if the client lands on a page that has a recipe listed. The application detects that feature and gives the user a pop-up that "a recipe has been found on this page, Would you like to add it?". I am a bit stuck on how to approach this problem. Any guidance in the right direction would be a great help. Kind Regards. Tech Stack is React Native on the Front-End and Django REST Framework on the backend -
Converting function based views to class based views
I'm trying to convert this function based view to a class based view by using the existing CreateView functionality: def manager(request): if request.method == 'POST': if request.POST.get('q3_name3[first]'): SEND = Manager() SEND.first_name = request.POST.get('q3_name3[first]') SEND.last_name = request.POST.get('q3_name3[last]') SEND.gender = request.POST.get('q4_gender4') SEND.address = request.POST.get('q6_address') SEND.phone_number = request.POST.get('q8_phoneNumber[full]') SEND.birth_date = request.POST.get('q9_birthDate') SEND.save() return render(request, 'manager.html') else: return render(request, 'manager.html') However I already have a form created using HTML and I've only come across tutorials that let Django automatically create the form. How can I use my existing form and convert this into a class based view using CreateView? Is there a way to tell Django to take this input box ID as the data in the Object? -
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) ]