Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to allow dependabot on GitHub to automatically "bump" software to new version?
Please help this learner out: I get frequent GitHub's dependabot alerts for "bumping" software versions to a more current one. My issue is I have to go into each (in my case, Django) app to pull or merge files. It tedious and time consuming to deal with my limited number of apps. How do professionals manage the process? Is there a way to allow GitHub just bump whatever needs to be bumped (assuming one doesn't mind apps being broken)? -
Django: convert DateField to string using DATE_FORMAT
I want to convert a Django DateField to a string according to the DATE_FORMAT as specified in settings.py, where I have a certain date format hard-coded. Can it be done without specifying a second (and at best superflous) date format for, e.g., strftime? -
Got an error creating the test database: database "DATABASE_NAME" already exists
I'm trying to run tests in my Django app and I suddenly started getting this error. When I go to run a test, it first tells me that the database already exists. Creating test database for alias 'default'... Got an error creating the test database: database "DATABASE_NAME" already exists Type 'yes' if you would like to try deleting the test database 'DATABASE_NAME', or 'no' to cancel: I type yes to delete the test database. At which point I get this error: Creating test database for alias 'default'... Traceback (most recent call last): File "/Users/x/Django/myapp/./manage.py", line 23, in <module> main() File "/Users/x/Django/myapp/./manage.py", line 19, in main execute_from_command_line(sys.argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 55, in handle failures = test_runner.run_tests(test_labels) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/runner.py", line 725, in run_tests old_config = self.setup_databases(aliases=databases) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/runner.py", line 643, in setup_databases return _setup_databases( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/test/utils.py", line 179, in setup_databases connection.creation.create_test_db( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/db/backends/base/creation.py", line 74, in create_test_db call_command( File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 181, in call_command return command.execute(*args, **defaults) File "/Users/x/Django/myapp/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute … -
Nginx, Gunicorn, Django, Postgresql concurrency handle?
I have so many confusion on my mind about concurrency handling . I am new about this concurrency handle so everything is feels like overwhelming . First thing is suppose I can handle 10k concurrent requests with nginx . (1) can Gunicorn handle 10k concurrent requests? (2) If Gunicorn can handle 10k requests how will posgresql response to this. (3) Did Django App Create new database connection for every request(unique user) ? If this happend, How will Postgres handle 10k connection ? -
Won't able to zoom after including chartjszoom in chartjs
Failed to zoom after include the correct version of chartjs and chartjs-plugin-zoom. <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.7/dist/chartjs-plugin-zoom.min.js"></script> This is my canvas tag <div class='chart-wrapper'> <div class="training-chart-area" style="width: 768px; height: 384px;"> <canvas id="trainingChart1"></canvas> </div> </div> My plugin option in my chart js function options: { plugins: { zoom: { zoom: { enabled: true, mode: 'y' }, pan: { enabled: true } } } I know I have the correct version because I tested it with another HTML file. I thought the problem may be chartjs-plugin-zoom won't work with multiple datasets within one chart, but test HTML worked perfectly fine. I have no idea where went wrong. -
How to filters field using django-filter
I need to create some filters for one table but cannot get it to work. When clicking on the Search button nothing happens. Ideally, I would like to get be able to select one or multiple category and get the results displayed with the number of objects counted. Did I missed anything in my code? Thank you models.py class Lead(models.Model): CATEGORY = ( (0, 'Education'), (1, 'Hotel'), (2, 'Construction'), (3, 'Residential'), (4, 'Facility Management'), ) businessname = models.CharField(max_length=150,blank=True, null=True) businesscategory = models.IntegerField(choices=CATEGORY, blank=True, null=True) filters.py import django_filters from .models import Lead class LeadFilter(django_filters.FilterSet): businessname = django_filters.CharFilter(lookup_expr='icontains') businesscategory = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Lead fields = ['businessname','businesscategory'] views.py @login_required(login_url="/login/") def index_leads(request): leads = Lead.objects.all() lead_filter = LeadFilter(request.GET, queryset=leads) context = { 'leads': leads, 'filter':lead_filter, } return render(request, 'analysis/index_leads.html', context) index_leads.html <form method="get"> <div class="container-fluid"> <h4 style="margin-top: 0"></h4> <div class="row"> <div class="form-group col-sm-3 col-md-3"> {{ filter.form.businesscategory.label_tag }} {% render_field filter.form.businesscategory class="form-control" %} </div> <div class="form-group col-sm-3 col-md-3"> {{ filter.form.businessname.label_tag }} {% render_field filter.form.businessname class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary float-right"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> -
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!