Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not saving forms data in database
I am getting forms success message in my html template but forms data not saving. here is my code: views.py: class BlogDetailsAccount(FormMixin,DetailView): model = Blog template_name = 'blog/my-account-blog-details.html' form_class = CommentFrom def get_success_url(self): return reverse('blog:my-account-blog-details', kwargs={'slug': self.object.slug}) def get_context_data(self, **kwargs): #my context data........ return data def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return self.form_valid(form) else: messages.add_message(self.request, messages.INFO, 'Somethings Wrong. Please try again') return self.form_invalid(form) def form_valid(self, form): return super(BlogDetailsAccount, self).form_valid(form) my models.py: class BlogComment(models.model): .......#my models fields.... ............. post_save.connect(BlogComment.user_comment, sender=BlogComment) #using signals -
Filtering on a Window function in Django
I have the following model: class Foobar(models.Model): foo = models.IntegerField() And I figured out how to calculate the delta of consecutive foo fields by using window functions: qs = Foobar.objects \ .annotate( delta=F('foo') - Window(Lag('foo'), partition_by=F('variant'), order_by=F('timestamp').asc()) ) Now I only want the records from this where delta is negative: qs.filter(delta__lte=0) But as you might expect, this gives an error: django.db.utils.NotSupportedError: Window is disallowed in the filter clause. How can I do this filtering with the Django ORM? -
Uvicorn + Django + NGinx - Error 404 while handlind websocks
I am setting up a server with Nginx and Uvicorn to run a Django app with websockets. Everything goes well with normal http request and I can get my webpage but my websockets handshakes always end up with a 404 error. Everything goes well running with runserver. here is my asgi.py file import os import django django.setup() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import AERS.routing import Stressing.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AERS.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( Stressing.routing.websocket_urlpatterns ) ), # Just HTTP for now. (We can add other protocols later.) }) my settings.py ASGI_APPLICATION = 'AERS.asgi.application' redis_host = os.environ.get('REDIS_HOST', '127.0.0.1') CHANNEL_LAYERS = { 'default': { 'CONFIG': { 'hosts': [(redis_host, 6379)], }, 'BACKEND': 'channels_redis.core.RedisChannelLayer', }, } my nginx config file server { listen 80; server_name aers.box 10.42.0.1; location = /favicon.ico { access_log off; log_not_found off; } location ~ ^/static { autoindex on; root /home/AERS; } location ~ ^/ { include proxy_params; proxy_pass http://unix:/home/AERS/AERS.sock; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering off; proxy_pass http://unix:/home/AERS/AERS.sock; } location ~ ^/ws/ { proxy_pass http://unix:/home/AERS/AERS.sock; proxy_http_version 1.1; proxy_redirect off; proxy_buffering off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Upgrade … -
Why do errors differ when I interchange the order of the members of url patterns
Note: I'm not requesting for a help to fix the errors, but to ask the reason why they differ by interchanging the order of url patterns. The following is how my urls.py of my django application (basic_app) looks like: from django.urls import path, re_path from basic_app import views app_name = 'basic_app' urlpatterns = [ path('', views.SchoolListView.as_view(), name='list'), re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'), path('create/', views.SchoolCreateView.as_view(), name='create'), ] when I run the server and type in the url http://127.0.0.1:8000/basic_app/create/, it throws the following error: ValueError at /basic_app/create/ Field 'id' expected a number but got 'create'. Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/create/ Django Version: 3.2.4 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'create'. Interestingly when I interchanged the order of the 2nd and 3rd url patterns as follows: from django.urls import path, re_path from basic_app import views app_name = 'basic_app' urlpatterns = [ path('', views.SchoolListView.as_view(), name='list'), path('create/', views.SchoolCreateView.as_view(), name='create'), re_path(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'), ] I got a different error: ImproperlyConfigured at /basic_app/create/ Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited. Request Method: GET Request URL: http://127.0.0.1:8000/basic_app/create/ Django Version: 3.2.4 Exception Type: ImproperlyConfigured Exception Value: Using ModelFormMixin (base class of SchoolCreateView) without the 'fields' attribute is prohibited. I … -
Accessing submitted form data in separate Django view
I have looked around on SO for a solution to what seems to be a very simple question, but I've not been able to find anything matching. I'm making a simple recipe app in Django. I have made 3 models, one for recipe information like title etc, one foreignkey model for ingredients, and one foreignkey model for methods. From these I have made a model form for the recipe information and two formsets for the ingredients and methods. Everything is working fine on the form page and data is submitting and viewable in Django admin. Please see below my Django view. def make_recipe(request): if request.method == "GET": form = RecipeForm() iformset = IngredientFormSet() mformset = MethodFormSet() return render(request, 'recipes/create_recipe.html', { 'form':form, 'iformset':iformset, 'mformset':mformset,}) elif request.method == "POST": form = RecipeForm(request.POST) if form.is_valid(): recipe_card = form.save() iformset = IngredientFormSet(request.POST, instance = recipe_card) if iformset.is_valid(): ingredients = iformset.save() mformset = MethodFormSet(request.POST, instance = recipe_card) if mformset.is_valid(): methods = mformset.save() if form.is_valid() and iformset.is_valid() and mformset.is_valid(): return redirect('recipe_submitted') And my template: {% extends 'recipes/base.html' %} {% block content %} <form action="." method="post"> {% csrf_token %} <h1>Recipe Information</h1> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} {{ form.as_p }} <hr> <h2>Ingredients</h2> {{ … -
Django expects wrong format when validating modelform datefield
I have a page where the user inputs some dates in the dd/mm/yyyy format. In my settings file I have this: DATE_INPUT_FORMATS = ('%d/%m/%Y','%Y/%m/%d', '%Y-%m-%d',) I use the django bootstrap4 datetime picker plus The field renders as such: (i apologize about the screenshot, i couldnt copy the html without it being escaped and it looked extra-messy) The problem The problem is that when i input dates in dd/mm/yyyy format, it uses the american format (mm/dd/yyyy) to validate them. So if i enter 27/12/2021 it will try to save [day 12, month 27, year 2021] and fail the validation. Preventing the formset from being saved. What i don't understand is where in hell does django get the idea that it should use the american format to validate dates when I have set three separate DATE_INPUT_FORMATS and none of them are in the american format? Here an image showing that on the page the date is collected in the right format And the response : [{'start_date': ['Enter a valid date.'], 'end_date': ['Enter a valid date.']}] Forms this is where i am now: class EducationForm(forms.ModelForm): # def clean_start_date(self): # print(self.cleaned_data['start_date']) # return datetime.strptime((self.cleaned_data['start_date']), '%Y-%m-%d') # def clean_end_date(self): # return datetime.strptime((self.cleaned_data['end_date']), '%Y-%m-%d') class Meta: … -
How to send emails every day to subscribed users of a website with python and django?
I want to create some backend code that will send a different email to each subscribed user of my website every day. I am currently using django and want to understand the basic idea of how I can go about making such a backend. Thanks in advance -
How can save encrypted data in db using django
I am trying to save encrypted data in db but it show the error raise DjangoCryptoFieldsKeyPathDoesNotExist( django_crypto_fields.key_path.DjangoCryptoFieldsKeyPathDoesNotExist: Key path does not exist. Got '/KEY_PREFIX.bin' I am using crypto.cipher for encryption. My data is encrypted in salsa20 but it is not saved in db in encrypted form now i use EncyptedTextField, now it show the error Setting.py INSTALLED APPS =[ 'django_crypto_fields.apps.AppConfig', ] KEY_PREFIX.bin Model.py From django_crypto_fields.fields import EncryptedTextField class StoreOrder(models.Model): items = EncryptedTextField(max_length=100) quantity = models.BigIntegerField() dateTime = models.DateTimeField(auto_now_add=True) completion = models.BooleanField(default=False) manager = models.ForeignKey(Store_Employee, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE) Store.py class Store_Order(LoginRequiredMixin, TemplateView): template_name = 'store/storeOrder.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request): data = self.request.POST.get userId = self.request.user.id managerId = Store_Employee.objects.get(user_id=userId) storeId = Store.objects.get(manager_id=managerId) try: secret = get_random_bytes(32) cipher = Salsa20.new(key=secret) storeOrder = StoreOrder( manager_id=managerId.id, store_id=storeId.pk, items=data('items'), quantity=data('quantity'), ) dat: str = storeOrder.items orderData = dat.encode("latin-1") cipherData = cipher.nonce + cipher.encrypt(orderData) print(cipherData) file = open('KEY_PREFIX', "wb") file.write(cipher) file.close() storeOrder.save() -
How can I return a dict object from within to_representation method of RelatedField in Django rest framework? [closed]
I have a custom field like this: class TagField(serializers.RelatedField): def to_representation(self, value): resp = { 'name': value.name, 'categoryid': value.categoryid.pk } return resp I'm getting an error which says 'dict' object is not hashable. Why does this happen? How can I get it to work? -
Django QS filter by nested annotated field
I have two Django models: class User(models.Model): first_name = ... last_name = ... class Book(models.Model): authors = models.ManyToManyField(User) Now I want to add filtering Books by their author's full name (first_name + last_name). I've added FilterSet with following logic: qs_prefetched = queryset.prefetch_related( Prefetch("authors", User.objects.annotate(full_name=Concat('first_name', Value(' '), 'last_name'))) ).all().filter(authors__full_name__icontains=value) And when I try to filter in that way I have following error: django.core.exceptions.FieldError: Related Field got invalid lookup: full_name But field full_name is in authors values: (Pdb) qs_prefetched[1].authors.all()[0].full_name 'Ke Xu' Can anybody tell what I'm missing? Thanks in advance. -
Django Send Mail in IIS 10
My company requires production/development in IIS. I've developed an app that sends email notifications on form submittal. Emails are sent with a google mail account. It works great when I run the app on the django development server (manage.py runserver). When I run the app on IIS server, I am unable to send emails. I get the SMTPSenderRefused 530, b'5.7.0 Authentication Required error. I have searched hi and low for documentation that would address this problem, with no luck. Since django is sending the email through its django.core.mail.backends.smtp.EmailBackend, I wouldn't think I need to do any settings in IIS (i.e. web.config file etc)? Any suggestions of where to read up would be great. Thank you. -
facing this python Django error img attached
def predict_Model(pclass,sex,age,sibsp,parch,fare,embarked,title): import pickle x = [[pclass,sex,age,sibsp,parch,fare,embarked,title]] rf = pickle.load(open('ML_titanic_Model.sav','rb')) prediction = rf.predict(x) if prediction == 1: prediction = 'Survived' elif prediction == 0: prediction = 'Not Survived' return prediction [enter image description here][1] Image attached here [1]: https://i.stack.imgur.com/eygY8.png -
django.db.utils.ProgrammingError: relation x does not exist
Apologies if this question has already been asked, however I could not find a working solution among the answers. I have the 'training_log' app, also added in the project's settings.py. In training_log\models.py: class SessionType(models.Model): name = models.CharField(max_length=80) def __str__(self): return f"{self.name}" class Exercise(models.Model): name = models.CharField(max_length=100) session_type = models.ForeignKey(SessionType, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class TrainingLog(models.Model): session_type = models.ForeignKey(SessionType, on_delete=models.CASCADE, null=True) exercises = models.ManyToManyField(Exercise) comments = models.TextField(max_length=500) date_posted = models.DateField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): exercises = ', '.join(str(ex) for ex in self.exercises.all()) return f"{self.session_type}- {self.date_posted}- {exercises}" I am using postgresql. When I try to run the makemigrations command, I get this error: django.db.utils.ProgrammingError: relation "training_log_sessiontype" does not exist LINE 1: ...ype"."id", "training_log_sessiontype"."name" FROM "training_... Before using postgresql, I was using sqlite3, and the migrations worked only if I added the models one by one and ran migrations after each of them. I have tried deleting the db files and the migrations folders to no avail. Could anyone please shed some light on this issue? Thank you in advance. -
Why celery not executing parallelly in Django?
I am having a issue with the celery , I will explain with the code def samplefunction(request): print("This is a samplefunction") a=5,b=6 myceleryfunction.delay(a,b) return Response({msg:" process execution started"} @celery_app.task(name="sample celery", base=something) def myceleryfunction(a,b): c = a+b my_obj = MyModel() my_obj.value = c my_obj.save() In my case one person calling the celery it will work perfectly If many peoples passing the request it will process one by one So imagine that my celery function "myceleryfunction" take 3 Min to complete the background task . So if 10 request are coming at the same time, last one take 30 Min delay to complete the output How to solve this issue or any other alternative . Thank you -
Django Slugify not loading categories with two words
I add the category section in the model and the slugify function loads posts with one-word category but it's not loading the posts with multiple words View Function: def CategoryView(request, cats): category_posts = Item.objects.filter(item_category__slug=cats.replace('-', '')) return render(request, 'waqart/categories.html', {'cats':cats, 'category_posts':category_posts }) Model: class Categories(models.Model): name = models.CharField(max_length=200) summary = models.CharField(max_length=200) slug = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name -
Saving form data to models.ForeignKey fields
I am working on a web-app which store books details.I created a form page to add details of books in database. when i am submitting that form it gives me error. valueError: Cannot assign "'scifi'": "Book.genre" must be a "Genre" instance. Is there any way to assign data from submitted form to the models.ForeignKey(Genre,on_delete=models.CASCADE,null=True) which is in Book class. models.py class Genre(models.Model): title=models.CharField(max_length=100) class Meta: verbose_name_plural='2. Genre' def __str__(self): return self.title class Language(models.Model): title=models.CharField(max_length=100) class Meta: verbose_name_plural='3. Language' def __str__(self): return self.title class Book(models.Model): image=models.ImageField(upload_to="book_imgs/",null=True) title=models.CharField(max_length=200,null=True) Author=models.CharField(max_length=200,null=True) genre=models.ForeignKey(Genre,on_delete=models.CASCADE,null=True) language=models.ForeignKey(Language,on_delete=models.CASCADE,null=True) class Meta: verbose_name_plural='1. Book' def __str__(self): return self.title def image_tag(self): return mark_safe('<img src="%s" width="50" height="50" />' % (self.image.url)) views.py def add_books(request): if request.method =="POST": bookname= request.POST['bookname'] author= request.POST['author'] genre= request.POST['genre'] language= request.POST['language'] instance = Book(title=bookname,Author=author,genre=genre,language=language) instance.save() return render(request,'Add_books.html') -
Django always throwing weird errors with all its command
django-admin startproject is the only command that ran successfully i am on 3.9.6 tching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/usr/local/lib/python3.9/site-packages/django/db/models/options.py", line 207, in contribute_to_class self.db_table = … -
Fetch subset columns from a Django API
I would like to get some columns of my Django API data. How can I do to get specific column without pulling all data as the does the following script ? var data_from_api; fetch('http://127.0.0.1:8000/api/network/1/edges/') .then((response) => { return response.json() }) .then((data) => edges_from_api=data) I just want to get lanes, length and speed. Subset of my api data [ { "id": 1, "edge_id": 1, "name": "Out 1 - E", "length": 4.0, "speed": 50.0, "lanes": 1, "param1": 3000.0, "param2": null, "param3": null, "road_type": 2, "source": 1, "target": 2 }, { "id": 2, "edge_id": 2, "name": "Out 1 - NE", "length": 4.0, "speed": 50.0, "lanes": 1, "param1": 3000.0, "param2": null, "param3": null, "road_type": 2, "source": 1, "target": 3 }, -
Problems Deploying Django, Gunicorn docker image to Kubernetes through rancher
I am having problems getting my docker image deployed on RKE. My docker image is a django application being served using gunicorn. I am using gitlab CI to test the app, build the container, and hold the container (in the gitlab container registry) it passes all the tests and builds the container successfully. When I go to deploy it on rancher it pulls the image just fine and builds the container but I keep getting an error that the gunicorn executable cannot be found. I have tried all the different types of configs for the CMD/ENTRYPOINT and I keep getting the error. Any help would be amazing as I am banging my head against the wall. Dockerfile is below: FROM python:3.8.5-slim-buster # install dependencies RUN apt-get -y update && apt-get -y upgrade && apt-get install -y musl-dev libpq-dev gcc ENV VIRTUAL_ENV=venv RUN python3 -m venv $VIRTUAL_ENV RUN echo $PATH ENV PATH="$VIRTUAL_ENV/bin:$PATH" RUN echo $PATH RUN ls -hal RUN pwd # Install dependencies: COPY requirements.txt . RUN pip install -r requirements.txt RUN ls -hal RUN ls -hal venv/bin RUN which gunicorn # copy project COPY . . EXPOSE 8080 CMD /venv/bin/gunicorn --bind :8080 django_app.wsgi Requirements.txt below (it is a bit messy … -
Two Ways to Handle a Request - Just Written Differently
I was looking at some different code on github and came across something that was confusing. Is there any differences between the code below? class RandomView(View): def get(self, *args, **kwargs): return render(self.request, 'random_template.html) Versus class RandomView(View): def get(self, request, *args, **kwargs): return render(request, 'random_template.html) To me this would do the same thing but to be fair my knowledge is pretty limited. Is one considered bad practice? Or maybe just preference? -
Django: Model relationship issues
I'm trying to get user invoices, expenses, withdrawals via celery tasks. After collecting all the data celery should send an email and etc... So the thing is that I've been stuck for a couple of days with the relationship that Django provides. I have missed a course about Django relationships, so I can't process it further. This is our project scheme: This is our models: class User(AbstractUser): username = None email = models.EmailField('email address', blank=True) phone = PhoneNumberField(unique=True) companies = models.ManyToManyField(Company, related_name='users') active_company = models.OneToOneField(Company, null=True, related_name='active_user', on_delete=models.SET_NULL) class InvoiceItem(BaseModel): objects = InvoiceItemManager() archives = InvoiceItemArchiveManager() invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='invoice_items') item = models.CharField(max_length=255) class Invoice(Operation): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='invoices', null=True, blank=True) class Merchant(BaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='merchants') name = models.CharField(max_length=255) company_code = models.CharField(max_length=255, default='', blank=True) def __str__(self): return f'{self.company} {self.name}' class Expense(Operation): category = models.CharField(choices=ExpenseCategories.get_choices(), default=ExpenseCategories.GENERAL.name, db_index=True, blank=True, max_length=255) merchant = models.ForeignKey(Merchant, on_delete=models.PROTECT, related_name='expenses', blank=True, null=True) class ExpenseReceipt(BaseModel): objects = ExpenseItemManager() archives = ExpenseItemArchiveManager() expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name='receipts') This is what I've tried: # Get Invoices that were created in one week start_date = timezone.now() - timedelta(weeks=1) # .filter(created_at__range=(start_date, timezone.now()) invoices = InvoiceItem.objects.select_related('invoice').annotate( total_invoices=Sum('invoice'), ) -
Can a server execute a script (stored remotely on the server) on a client's machine?
Here's the entire desired process: I have a client-server architecture where the server is implemented using Django. The client (located outside the server's network): Connects to my server from a browser; Executes a script to package the images and other necessary files for the processing; Upload the packaged files to my server; My server processes the images; My server sends the processed images back to the client. My question is: can the server execute in anyway the script/executable that does the packaging on the client's machine? The script would be in Python or C. The main reason behind this question is that I want my script to remain on the server's side and I want to keep the client as thin as possible; I don't want to keep anything on the client's side except the package the script would generate and the returned data from the processing. I started looking into RPyC, but since I have very little insight into how I could do this, I am here gathering suggestions. -
How to set Heroku app to specific Postgres schema?
There is one database configured in Heroku. The Django application connects fine, but the tables are put in the public schema. These tables should be in the 'invoices' schema. That schema is already created, but it's empty. Below is what the settings.py currently look like: DATABASES["default"] = dj_database_url.config( conn_max_age=600, ssl_require=True, ) DB_SEARCH_PATH = os.environ.get("DB_SEARCH_PATH", "invoices") -
Django- Home Html gets empty list space while trying to print this team name as list
**Below is my code. Let me know how to get the team name alone printed View.py teams = {"P51AXX":"ECE","PZXXXXX":"Kafka","PAZZXXXX":"CDC","PDXXX":"HCC","PZIXXXX":"BDPaaS", "P18XXX":"API Gateway","PXXPXXX":"Stargate","PHHXXX":"Messaging Queue"} def home(request): list_teams = "" team_list = list(teams.values()) for team in team_list: #capitalized_team = team.capitalize() list_teams += f"<li><a href=>{team} </a><li>" data_1 = f"<ul>{list_teams}</ul>" return render(request,'home.html',{'data':data_1}) home.html : <!DOCTYPE html> <html> <body> <h1 style="text-align:center">PEP Metrics</h1> <p>Click the Below team to get Pagerduty counts</p> {{data|safe}} </body> </html> Image -
Django ORM Syntax for 'LIKE' queries with respect to Datetime
I have this table which has column "date" in the format "2021-03-12 08:12:44.350176". I want to compare a external date such as "2021-03-12 08:12:44" I have tried this new_date = datetime.datetime(2021, 3, 12, 8, 12, 44, tzinfo=<UTC>) obj = Test.objects.filter(date__contains=new_date).all() But it doesn't work, it returns empty sets. My goal is to fetch all the records against the new_date. Is there a way to remove milliseconds or way to compare the two dates?