Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload multiple files (images) using django-rest-framework?
I'm writing a REST API, I haven't tried and have no clue how to upload multiple photos using django. Is there a separate serializer that I have to use or can I just use the serializer with the param 'many=True' similar to bulk data insertion? A python snippet would really be useful. Thanks in advance! -
Reverse access to OneToOne field in an abstract model
Suppose I have the following database structure: class Building(models.Model): # ... class AbstractBuilding(models.Model): building = models.OneToOneField(Building, on_delete=models.CASCADE, primary_key=True) # ... class Meta: abstract = True class Office(AbstractBuilding): # ... class Lab(AbstractBuilding): # ... class PowerPlant(AbstractBuilding): # ... If I have an Office object, it's easy to get the corresponding Building through the one-to-one field (e.g. office_object.building returns a Building). However, suppose I have a Building instead. How can I get the corresponding Office (or Lab or PowerPlant) from the Building object? -
No module named 'django.contrib.staticfiles.templatetags'
I have been breaking my head over this for a full day but can't figure out the problem. It happened after I copied my Django project from one PC to another. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/username/opt/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/username/opt/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/Users/username/opt/anaconda3/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Users/username/opt/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/saitohiromasa/opt/anaconda3/lib/python3.7/site-packages/django_summernote/admin.py", line 5, in <module> from django_summernote.widgets import SummernoteWidget, … -
How can i reduce my coding length in my below code?
Because i am a newbie so its really hard to understand code having much length..If i can reduce the length of code then how can i reduce it please explain someone in the below code. class Attachments(models.Model): created_by = models.ForeignKey( User, related_name='attachment_created_by', on_delete=models.SET_NULL, null=True) file_name = models.CharField(max_length=60) created_on = models.DateTimeField(_("Created on"), auto_now_add=True) attachment = models.FileField( max_length=1001, upload_to='attachments/%Y/%m/') lead = models.ForeignKey( 'leads.Lead', null=True, blank=True, related_name='lead_attachment', on_delete=models.CASCADE) account = models.ForeignKey( 'accounts.Account', null=True, blank=True, related_name='account_attachment', on_delete=models.CASCADE) contact = models.ForeignKey( 'contacts.Contact', on_delete=models.CASCADE, related_name='contact_attachment', blank=True, null=True) opportunity = models.ForeignKey( 'opportunity.Opportunity', blank=True, null=True, on_delete=models.CASCADE, related_name='opportunity_attachment') case = models.ForeignKey( 'cases.Case', blank=True, null=True, on_delete=models.CASCADE, related_name='case_attachment') task = models.ForeignKey('tasks.Task', blank=True, null=True, related_name='tasks_attachment', on_delete=models.CASCADE) invoice = models.ForeignKey('invoices.Invoice', blank=True, null=True, related_name='invoice_attachment', on_delete=models.CASCADE) event = models.ForeignKey('events.Event', blank=True, null=True, related_name='events_attachment', on_delete=models.CASCADE) def file_type(self): name_ext_list = self.attachment.url.split(".") if (len(name_ext_list) > 1): ext = name_ext_list[int(len(name_ext_list) - 1)] if is_document_file_audio(ext): return ("audio", "fa fa-file-audio") if is_document_file_video(ext): return ("video", "fa fa-file-video") if is_document_file_image(ext): return ("image", "fa fa-file-image") if is_document_file_pdf(ext): return ("pdf", "fa fa-file-pdf") if is_document_file_code(ext): return ("code", "fa fa-file-code") if is_document_file_text(ext): return ("text", "fa fa-file-alt") if is_document_file_sheet(ext): return ("sheet", "fa fa-file-excel") if is_document_file_zip(ext): return ("zip", "fa fa-file-archive") return ("file", "fa fa-file") return ("file", "fa fa-file") def get_file_type_display(self): if self.attachment: return self.file_type()[1] return None @property def created_on_arrow(self): return … -
Migrating to Django 2.2 from 1.11 -- old migrations without on_delete in ForeignKey break everything
I'm working on upgrading my legacy application from Django 1.11.13 to 2.2.8. I've dutifully addressed every compatibility issue, but I've hit one I can't figure out how to resolve. When I try to start the webserver in my local environment, I get this error (only showing the end of the full error trace that appears): File "/Users/me/my_app/my_model/migrations/0001_initial.py", line 37, in Migration ('entry', models.ForeignKey(to='my_model.Entry')), TypeError: __init__() missing 1 required positional argument: 'on_delete' I understand why on_delete is now required -- I just spent a while updating my models everywhere to accommodate this change -- but I have no idea how to fix this particular issue without going through dozens of old migrations files to make them conform?! I tried squashmigrations to at least collapse the number of places I have to clean up, but I got the same exact TypeError. I tried to use the old version of Django for squashmigrations. I was successful in avoiding the TypeError, but ended up with a huge mess of circular import errors. Since I don't actually need the migration history to roll back, I tried to follow these instructions (scenario 2) to clear the migration history while keeping the existing database, but I couldn't … -
Can I post the javascript array to the database in django framework?
I am new to django, I am having an users table and designs table as given below class designs(models.Model): id=models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') > class users(models.Model): email = models.CharField(max_length=50,default='0000000') password = models.CharField(max_length=50,default='0000000') design = models.ManyToManyField(designs) The user will click the designs he want it is a multi select and after clicking every the every design i wrote a javascript array to store the details of every design clicked by the user like this styles=[2, "../static/images/2.jpg", "Rustic & Warm", 3, "../static/images/3.jpg",…] So,in the form I took hidden input of design_id like this <form action="{% url 'car:user_register' %}" method="POST"> > {% csrf_token %} > <div class="form-group"> > <label for="design_id"></label> > <input type="hidden" name="design_id" class="form-control" value="styles"required> > </div> > > And my views.py def user_register(request): if request.method == 'POST': design_id=request.POST.GET('styles[]') email = request.POST['email'] password = request.POST['password'] user = users(password=password,email=email,design_id=design_id) user.save() return render(request,'home.html') Is that a correct way of getting and posting that javascript array in the database -
How to populate initial values of form from queryset
I have a FormView with a get_initial method which I am trying to use to populate the form. I am trying to get the EmployeeTypes of the receiver of the memo as values in the form. def get_initial(self): initial = super(NotificationView, self).get_initial() users = Memo.objects.filter(id=self.kwargs['pk']).values('receiver__employee_type') initial['receiving_groups'] = users return initial There are 2 issues here.. This returns a Queryset which looks like: <QuerySet [{'receiver__employee_type': 'Bartender'}, {'receiver__employee_type': 'Supervisor'}]> when I really need the fields in the form to be the EmployeeType itself. Most importantly - the form isn't even rendering these fields. Here is the form just in case: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) How do I populate the fields of the form? -
Error while updating mongodatabase collections from django app using djongo
I am facing an error. I am trying out the polls tutorial as provided in the django documentation. The problem is with the django 'F' function. I am trying to update the number of votes for a choice. If I load the choice object into python memory and do the normal numeric addition it is working. But if I use choice.update(votes=F('votes')+1) then it is giving me the following error. djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "poll_choice" SET "question_id" = %(0)s, "choice_text" = %(1)s, "votes" = ("poll_choice"."votes" + %(2)s) WHERE "poll_choice"."id" = %(3)s Params: (1, 'huntress', 1, 3) If we observe %(2)s is supposed to be a number and not a string. But it is going as a string. Please help how I can resolve this . I am using djongo 1.2.38 with sqlparse version 0.2.4. -
Django Model seeking alternative to many to many fields
I am writing an exam system, below is my model: class Exam(models.Model): name = models.CharField( max_length=100 ) class Topic(models.Model): name = models.CharField( max_length=50 ) class Question(models.Model): title = models.CharField( max_length=100 ) topic = models.ForeignKey( Topic ) class Choice(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE ) choice_text = models.CharField( max_length=200 ) is_right_answer = models.BooleanField( default=False ) I want when I create an exam, i can give multiple topics like math, physics, business etc and then i can query all the questions related that topics and show in the frontend. My problem only in exam creation, i am not getting should I use ManyToManyField or there is any alternative solution I just want to select multiple topic during i create an exam. Can anyone help me in this case? -
Why is my Django form is not displaying anything?
I am following a tutorial in which we will create a form to hold simple object parameters. Here's the code: forms.py from django.forms import ModelForm from .models import Item class ItemForm(ModelForm): class Meta: model = Item fields = ['item_name', 'item_desc', 'item_price', 'item_image'] models.py from django.db import models class Item(models.Model): def __str__(self): return self.item_name item_name = models.CharField(max_length = 200) item_desc = models.CharField(max_length= 200) item_price = models.IntegerField() item_image = models.CharField(max_length=500, default ="https://i.jamesvillas.co.uk/images/jvh/holiday-destinations/resort/food-placeholder.jpg" ) urls.py from . import views from django.urls import path urlpatterns = [ path('', views.index, name = 'index'), path('item/', views.item, name = 'item'), path('info/', views.info, name = "info"), path('<int:item_id>/', views.detail, name = "detail" ), #add form path('add', views.create_item, name = "create"), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item from django.template import loader from .forms import ItemForm #Some code here def create_item(request): form = ItemForm(request.POST or None) if (form.is_valid()): form.save() return redirect('food/index') return render(request, 'food/item-form.html', {'form': form}) food/item-form.html <form method = "POST"> {% csrf_token %} {{ form }} <button type= "Submit" >Save</button> </form> Now when I go to http://localhost:8000/food/add, it displays an empty page! I have followed the tutorial the exact same way then why is My project not working? -
Join and format array of objects in Python
I want to join and format values and array of objects to a string in python. Is there any way for me to do that? url = "https://google.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" } ] url = "https://google.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "Chennai Express", "rating": "5.0" } ] url = "https://bing.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "1.5" }, { "restaurant": "Bangkok Palace", "rating": "4.5" } ] url = "https://bing.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "4.5" }, { "restaurant": "Chennai Express", "rating": "3.0" } ] I want to be able to format the values as such: If I could make it look like: all_data = [{ url = "https://google.com", results = [{ search = "thai food", search_res = [{ "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" }] }, { search = "Indian food", search_res = [{ "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "CHennai Express", "rating": "5.0" }] }] }, { url = "https://bing.com", … -
Webhost Platform for PostGIS, Django and Celery
I'm currently developing a django web app. I'm trying to decide which platform is best suited to host it. I was considering PythonAnywhere but it seems like they don't support celery or other long running processes. Any suggestions? -
How to initialize form with some parameters of model instance
I would like be able to send SMS/Email notifications manually using the groups/users of a model instance. Let's say the model looks like this: class Memo(models.Model): title = models.CharField(max_length=100) receiver = models.ManyToManyField(EmployeeType, related_name='memos_receiver') I pass the object instance to the view: path('<int:pk>/notify', NotificationView.as_view(), name='memos-notify'), The form and the view are where I am having trouble. I figure I should be able to just pass the forms initial fields right there in the view: class NotificationView(FormView): template_name = 'memos/notification_form.html' form_class = MemoNotificationForm success_url = reverse_lazy('overview') def get_initial(self): initial = super(NotificationView, self).get_initial() memo = Memo.objects.filter(id=id) initial['receiving_groups'] = memo.receiver return initial And the form looks like this: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Do I need to initialize the queryset in the form? Would appreciate it if someone could paint me a clear picture of the why and how here. Thank you! -
Crispy Django Form With RadioBox - Using InlineRadios
I want to style in Radio button in Django using Crispy Form. However, I have successful making use of CSS which is applied to the form but I need to display the form n inline format. After rendering the form in my html, I got a put which is not in inline format. I will be very happy if I can more detail about crispy form using radio button or selected button class ViewForm(forms.Form): #django gives a number of predefined fields #CharField and EmailField are only two of them #go through the official docs for more field details VIEWS = ( ('1', 'Likes & Comments'), ('2', 'Subscribers'), ('2', 'App Installs'), ) GENDER = ( ('1', 'Female'), ('2', 'Male') ) AGE = ( ('All', 'All'), ('13 - 24', '13 - 24'), ('25 - 34', '25 - 34'), ('35 - 44', '35 - 44'), ('45 - 54', '45 - 54'), ('55 - 64', '55 - 64'), ) CATEGORY = ( ('Auto', 'Auto'), ('Beauty', 'Beauty'), ('Sport', 'Sport'), ) CHOICES=[('select1','select 1'), ('select2','select 2')] view= forms.ChoiceField(label='BESIDE VIEWS, I ALSO WANT:', widget=forms.RadioSelect, choices=VIEWS) age= forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=AGE) gender = forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=GENDER) location = forms.CharField(max_length=25, required=False) category= forms.CharField(label='CATEGORY', widget=forms.Select(choices=CATEGORY)) keyword = forms.CharField(max_length=50, required=False) my css input[type=radio], … -
Django TestCase object has no attribute 'login'
I have used selenium to test my login method and it works fine. Then, I tried to test other parts of the website. So, I needed to create a user in my test. To do that, I've used client instead of request factory (since there are middleware classes). However, I am getting the error: AttributeError: 'ProjectListTestCase' object has no attribute 'login' I do have a custom authentication backend to allow for email address to be used instead of username: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'rest_framework', # 3rd party apps 'crispy_forms', # Local apps 'accounts', ... I tried the code in the console: >>> the_client = Client() >>> the_client.login(email='test@testing.com', password='testingPassword') True Here is the code in my test_views.py: from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.test import TestCase from django.test import RequestFactory from model_mommy import mommy from selenium import webdriver from project_profile.models import Project from user_profile.models import UserProfile class ProjectListTestCase(TestCase): def setUp(self): # login the user login = self.client.login(email='test@testing.com', password='testingPassword') print ('Login successful? ', self.login) # Just to see what's going on response = self.client.get(reverse('development:list_view_developmentproject') ) print('response: ', self.response) # Just to see what's going on def test_user_login(self): self.assertEqual(self.response.status_code, 200) Why do I … -
Send mail inside action django-rest-framework
i'm learning django restframework by myself I'm trying to send a mail with sengrid inside an action enter image description here The mail doesn't send Sorry for menglish thank you -
Django background task repeating more than it should
I am trying to run a django background task every 30 seconds, as a test I'm having it print "hello", but instead of printing every 30 seconds it is printing about every second or less very quickly. Here is my code currently: from background_task import background from datetime import timedelta, datetime @background(schedule=datetime.now()) def subscription_job(): print("hello") subscription_job(repeat=30) -
How to make the user visible to al his group activities
I am doing a django-rest-framework project in which one can create groups by adding member’s email id and the logged in user should be able to see all the group activities. I used django-multi-email-field to store the list of emails of respective members Now the user can see his own activities when logged in.How can i make the user visible to all the group activities.Should i create a model inside a model? Please help me. -
Failed lookup for key in templates
I am trying to get Specific List in Dictionary, but first i got the error: "fail to lookup for key", searching on internet I found out a tread with this solution: {% with obj1.page.val2 as val2 %} {{ obj1.val1|default:val2 }} {% endwith %} But It does not work any help here is my code: keyData = '\'' + id + '|' + id2 + '|' + id3 + '\''; console.log(keyData); var val2; try { {% with keyData as val2 %} console.log(val2); datas = {{product_prices_complex_key|get_item:val2|safe}}; {% endwith %} console.log(datas); }catch(err){console.log(err);} KeyData: WA5-8|2|5 And is in the dictionary. Thanks in Advanced -
Django model method error: missing 1 required positional argument: 'self'
I want to do some calculations inside a model and between attributes. I want 3 fields that can be entered by the user to add the model, but those fields get concatenated into a non-editable field that can be used for viewing purposes only. Here is the model I have: class Dossier(models.Model): #Dossiers sinistre numero = models.CharField(max_length=20, default=dossier_number, editable=False) created_by = models.ForeignKey(Prestataire, on_delete=models.SET_NULL, null=True) mat_id = models.CharField(max_length=7, default="123456") mattypes = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ) mat_symbol = models.CharField(max_length=3, choices=mattypes, default="A") mat_ville = models.CharField(max_length=2, blank = True) def define_matricule(self): if self.mat_symbol == "A" or "B": return str(self.mat_id) + '-' + str(self.mat_symbol) + '-' + str(self.mat_ville) else: return str(self.mat_id) + '-' + str(self.mat_symbol) matricule = models.CharField(max_length=20, default=define_matricule, editable=False) But when I run this, I find this error: Django Version: 2.2.5 Exception Type: TypeError Exception Value: define_matricule() missing 1 required positional argument: 'self' Exception Location: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py in get_default, line 797 Python Executable: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\python.exe Here's my traceback: Environment: Request Method: GET Request URL: http://localhost:8000/dossiers/nouveau Django Version: 2.2.5 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'formtools', 'dashboard.apps.DashboardConfig', 'crispy_forms', 'photologue', 'sortedm2m'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" … -
get_decoded method show "Session data corrupted" in Django session
I have an application which using Django 2.0 and I'm facing with an issue about session data today. (SECRET_KEY is a static string, and consistent among the app so this might not is the issue) The command I've tried is: from django.contrib.sessions.models import Session session = Session.objects.first() session.get_decoded() # Session data corrupted # {} Even when I clear all the sessions, login again for a new session but still facing the same issue. I really want to read the session from the backend using manage.py shell and those script above. -
How to return user session id alongside Django rest serializer output
I'm writing a web application with Django. In one of my APIs which is using Django rest_framework, I want to return user's session ID alongside the default response. I know how to get the session ID but I don't know how to put it alongside the response(for example, in a JSON format) This is my code: class HouseInfoSerializer(serializers.ModelSerializer): class Meta: model = House fields = '__all__' class HouseViewSet(generics.ListAPIView): serializer_class = HouseInfoSerializer def get_queryset(self): postcode = self.kwargs['postcode'] print(self.request.session.session_key, "*"*10) return House.objects.filter(postcode=postcode) -
python - group values when generating a json
I am generating below JSON using a piece of code. Basically, I need to group my generated JSON group by continent, and then country and languages [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us" } ] }, { "region": "ar", "country": "Argentina", "languages": [ { "language": "es-ar" } ] }, { "region": "bo", "country": "Bolivia", "languages": [ { "language": "es" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "en-us" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "pt-br" } ] } ] }} I am generating above JSON using the below code. def get_available_locales_json(): locales = [] for locale in get_available_locales(): append_locale = True for entry in locales: if entry['continent'] == locale.region.continent: entry['regions'].append({'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}) append_locale = False break if append_locale: locales.append( { 'continent': locale.region.continent, 'regions': [{'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}] } ) return locales However, I need to group languages together without having an extra node for the country. something like below, [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us", "language": "es-ar" } … -
How can I convert a duration or a string to an integer in a queryset in Django views.py?
I need to calculate the time difference between two rows. This duration then needs to be adjusted up to 1 if the total is 0, or if the total is over 15 minutes, adjusted to 0--I was going to put this corrected amount in strtime. Unfortunately, my calculated times are not correct nor can I convert the extracted minutes to an integer in order to test if the duration is > 15 or < 1. The only reason I converted to a string was to see if I could then convert to an integer--it didn't work. I also tried to convert to a pandas dataframe in order to do the calculations, but I could not get it back into some format to display properly on the html page. How can I do an accurate calculation between rows and how can I adjust from 0 to 1 or > 15 to 0? I have tried many different versions--just not having much luck. I normally work in javascript--this is my first Django project. I have sanitized and shortened the data. This page will fit into an existing Django setup. Thank you in advance! Code is below. models.py class testmodels(models.Model): primary_key_id = models.CharField(max_length=150, … -
Django queryset caching with exists()
Let's say, I'm trying to change the name of all profiles whose name is John to Mike queryset = Profile.objects.filter(name='John') Method 1: if queryset: queryset.update(name='Mike') Method 2: if queryset.exists(): queryset.update(name='Mike') QUESTION: Which method is more efficient? Usually, I use exists() in the same line as my filter, so it queries once. However, I'm not sure if Method 2 will make another query to the database, making it less efficient.