Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
http://127.0.0.1:8000 does not match any trusted origins. Docker Django Nginx Gunicorn
I try to log in to the site admin, but display this. I have no clue, this is my code, can someone help me out!!! My All Code Here -
Django rest framework. How i can create endpoint for updating model field in bd?
I wanted to create an endpoint for article_views and update this field in db. I want to change this field on frontend and update it on db. When I go to url(articles/<int:pk>/counter) I want article_views + 1. model.py: Class Articles(models.Model): class Meta: ordering = ["-publish_date"] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255, unique=True) content = models.TextField() annonce = models.TextField(max_length=255, null=True) publisher = models.ForeignKey(User, on_delete= models.DO_NOTHING,related_name='blog_posts') publish_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) article_views = models.PositiveBigIntegerField(default=0) serializers.py: class ArticlesSerializer(serializers.ModelSerializer): tags = TagsField(source="get_tags") author = ProfileSerializer(source="author_id") class Meta: model = Articles fields = ('id','title', 'author', 'tags','annonce', 'content', 'categories', 'article_views') views.py class ArticlesViewSet(viewsets.ModelViewSet): queryset = Articles.objects.all().order_by('title') serializer_class = ArticlesSerializer -
CIDC with BitBucket, Docker Image and Azure
I am learning CICD and Docker. So far I have managed to successfully create a docker image using the code below: Dockerfile # Docker Operating System FROM python:3-slim-buster # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 #App folder on Slim OS WORKDIR /app # Install pip requirements COPY requirements.txt requirements.txt RUN python -m pip install --upgrade pip pip install -r requirements.txt #Copy Files to App folder COPY . /app docker-compose.yml version: '3.4' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 My code is on BitBucket and I have a pipeline file as follows: bitbucket-pipelines.yml image: atlassian/default-image:2 pipelines: branches: master: - step: name: Build And Publish To Azure services: - docker script: - docker login -u $AZURE_USER -p $AZURE_PASS xxx.azurecr.io - docker build -t xxx.azurecr.io . - docker push xxx.azurecr.io With xxx being the Container registry on Azure. When the pipeline job runs I am getting denied: requested access to the resource is denied error on BitBucket. What did I not do correctly? Thanks. -
Django 2.0 website running on a Django 4.0 backend
I am using an old version of Windows, windows 7 to be precise and it seems to only be compatible with Python 3.4 which supports Django 2.0 but heroku doesn't support it anymore So I want to know if I can manually edit the requirements to Django 4.0 and the required Python version in github. I haven't yet tried anything as I am new to this -
Django.models custom blank value
thanks for tanking the time to look at this query. I'm setting an ID field within one of my Django models. This is a CharField and looks like the following: my_id = models.CharField(primary_key=True, max_length=5, validators=[RegexValidator( regex=ID_REGEX, message=ID_ERR_MSG, code=ID_ERR_CODE )]) I would like to add a default/blank or null option that calls a global or class function that will cycle through the existing IDs, find the first one that doesn't exist and assign it as the next user ID. However, when I add the call blank=foo() I get an error code that the function doesn't exist. Best, pb -
How To add Multiple Languages to Web application Based on React and Django Rest API
I had an issue about makeing web application multi languages as I used React with DRF, is the locale way and messages correct to use ? how can I translate only the result data returned on response i sent to react and thank you so much -
printing values django templates using for loop
I have two models interrelated items and broken class Items(models.Model): id = models.AutoField(primary_key=True) item_name = models.CharField(max_length=50, blank=False) item_price = models.IntegerField(blank=True) item_quantity_received = models.IntegerField(blank=False) item_quantity_available = models.IntegerField(blank=True) item_purchased_date = models.DateField(auto_now_add=True, blank=False) item_units = models.CharField(max_length=50, blank=False) def __str__(self): return self.item_name item = models.ForeignKey(Items, default=1, on_delete=models.CASCADE) item_quantity_broken = models.IntegerField(blank=True) item_broken_date = models.DateField(auto_now_add=True, blank=False) item_is_broken = models.BooleanField(default=True) date_repaired = models.DateField(auto_now=True, blank=True) def __str__(self): return self.item.item_name I wrote this view function to retrieve data to a table into a template, def broken_items(request): br = Broken.objects.select_related('item').all() print(br.values_list()) context = { 'title': 'broken', 'items': br, } return render(request, 'store/broken.html', context) this is the executing query, SELECT "store_broken"."id", "store_broken"."item_id", "store_broken"."item_quantity_broken", "store_broken"."item_broken_date", "store_broken"."item_is_broken", "store_broken"."date_repaired", "store_items"."id", "store_items"."item_name", "store_items"."item_price", "store_items"."item_quantity_received", "store_items"."item_quantity_available", "store_items"."item_purchased_date", "store_items"."item_units" FROM "store_broken" INNER JOIN "store_items" ON ("store_broken"."item_id" = "store_items"."id") looks like it gives me all the fields I want.In debugger it shows data from both tables, so I wrote for loop in template, {% for item in items %} <tr> <td>{{item.id}}</td> <td>{{item.item_id}}</td> <td>{{item.item_quantity_broken}}</td> <td>{{item.item_broken_date}}</td> <td>{{item.item_is_broken}}</td> <td>{{item.date_repaired}}</td> <td>{{item.item_name }}</td> <td>{{item.item_item_quantity_received}}</td> <td>{{item.item_quantity_available}}</td> <td>{{item.item_purchased_date}}</td> <td>{{item.items_item_units}}</td> </tr> {% endfor %} The thing is this loop only gives me data from broken table only. I can't see data from Items table. can someone help me to find the reason why other details are … -
Question regarding the object getting serilaized in Django rest
Here I'm with a simple doubt where I'm completely confused. I have Model called ReviewsRatings to shows reviews based on each product.And created a Model Serializer ReviewSerilaizer. In views, am passing this ReviewsRatings instance to ReviewSerilaizer class ShowReviews(APIView): def get(self, request, *args, **kwargs): product_slug = self.kwargs["product_slug"] reviews = ReviewRatings.objects.filter(user=request.user, product__slug=product_slug) if not reviews: return Response([]) serializer = ReviewSerializer(reviews, many=True, context={'request':request}) return Response(serializer.data, status=status.HTTP_200_OK) #Serializer class ReviewSerializer(ModelSerializer): user = SerializerMethodField() class Meta: model = ReviewRatings fields = [ "user", "rating", "review", "created_at", "updated_at", ] def get_user(self, obj): return f"{obj.user.first_name} {obj.user.last_name}" So my doubt is in def get_user(self, obj) the obj is the product object which am getting. And in the views I,m filtering user = request.user along with product__slug=product_slug. So why Im not getting user object instead getting Products object Here is the Models. class ReviewRatings(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) product = models.ForeignKey(Products, on_delete=models.CASCADE) rating = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(5)]) created_at = models.DateField(auto_now_add=True) review = models.CharField(max_length=500, null=True) updated_at = models.DateField(auto_now=True) class Meta: verbose_name_plural = "Reviews & Ratings" def __str__(self): return self.product.product_name I don't know it's a dumb question to be asked or I didn't asked the question correctly. But this is making me so confused. -
why form.is_valid() is always false?
I tried to create a contact us form in django but i got always false when i want to use .is_valid() function. this is my form: from django import forms from django.core import validators class ContactForm(forms.Form): first_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خود را وارد کنید'}), label="نام ", validators=[ validators.MaxLengthValidator(100, "نام شما نمیتواند بیش از 100 کاراکتر باشد")]) last_name = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'نام خانوادگی خود را وارد کنید'}), label="نام خانوادگی", validators=[ validators.MaxLengthValidator(100, "نام خانوادگی شما نمیتواند بیش از 100 کاراکتر باشد")]) email = forms.EmailField( widget=forms.EmailInput( attrs={'placeholder': 'ایمیل خود را وارد کنید'}), label="ایمیل", validators=[ validators.MaxLengthValidator(200, "تعداد کاراکترهایایمیل شما نمیتواند بیش از ۲۰۰ کاراکتر باشد.") ]) title = forms.CharField( widget=forms.TextInput( attrs={'placeholder': 'عنوان پیام خود را وارد کنید'}), label="عنوان", validators=[ validators.MaxLengthValidator(250, "تعداد کاراکترهای شما نمیتواند بیش از 250 کاراکتر باشد.") ]) text = forms.CharField( widget=forms.Textarea( attrs={'placeholder': 'متن پیام خود را وارد کنید'}), label="متن پیام", ) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__() for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form_field require' this is my view: from django.shortcuts import render from .forms import ContactForm from .models import ContactUs def contact_us(request): contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): first_name = contact_form.cleaned_data.get('first_name') last_name = contact_form.cleaned_data.get('last_name') email = contact_form.cleaned_data.get('email') title = contact_form.cleaned_data.get('title') text = contact_form.cleaned_data.get('text') ContactUs.objects.create(first_name=first_name, last_name=last_name, email=email, … -
how to call a property from values in django
I need the value of the property, which calls through the values call so that later i will use in the union method so used model is class Bills(models.Model): salesPerson = models.ForeignKey(User, on_delete = models.SET_NULL, null=True) purchasedPerson = models.ForeignKey(Members, on_delete = models.PROTECT, null=True) cash = models.BooleanField(default=True) totalAmount = models.IntegerField() advance = models.IntegerField(null=True, blank=True) remarks = models.CharField(max_length = 200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) class Meta: ordering = ['-update', '-created'] def __str__(self): return str(self.purchasedPerson) @property def balance(self): return 0 if self.cash == True else self.totalAmount - self.advance when i call the model as bills = Bills.objects.all() I can call the balance property as for bill in bills: bill.balance no issue in above method but i need to use the bills in union with another model so needed fixed vales to call i am calling the method as bill_trans = Bills.objects.filter(purchasedPerson__id__contains = pk, cash = False).values('purchasedPerson', 'purchasedPerson__name', 'cash', 'totalAmount', 'id', 'created') in place of the 'totalamount' i need balance how can i approach this step -
Django cannot save a CharField with choices
I have this CharField with some choices: M = 'Male' F = 'Female' O = 'Other' GENDER = [ (M, "Male"), (F, "Female"), (O, "Other") ] gender = models.CharField(max_length=10, choices=GENDER) When I try and save a model in the database I get the following error: django.db.utils.DataError: malformed array literal: "" LINE 1: ...ddleq', 'Cani', '1971-09-01'::date, '{Male}', '', ''::varcha... ^ DETAIL: Array value must start with "{" or dimension information. The {Male} value is so because I made the front end send the value like that but it's not that and the error makes no sense. Please can someone tell me why am I getting this error and how to fix it pls? I use the Python 3.8 Django 4.1 PostGreSQL -
nginx unable to load media files - 404 (Not found)
I have tried everything to serve my media file but yet getting same 404 error. Please guide. My docker-compose file: version: "3.9" services: nginx: container_name: realestate_preprod_nginx_con build: ./nginx volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.8 expose: - 8000 depends_on: - realestate_frontend - realestate_backend real_estate_master_db: image: postgres:latest container_name: realestate_master_db_con env_file: - "./database/master_env" restart: "always" networks: glory1network: ipv4_address: 10.1.1.5 expose: - 5432 volumes: - real_estate_master_db_volume:/var/lib/postgresql/data real_estate_tenant1_db: image: postgres:latest container_name: realestate_tenant1_db_con env_file: - "./database/tenant1_env" restart: "always" networks: glory1network: ipv4_address: 10.1.1.9 expose: - 5432 volumes: - real_estate_tenant1_db_volume:/var/lib/postgresql/data realestate_frontend: image: realestate_web_frontend_service container_name: realestate_frontend_con restart: "always" build: ./frontend command: bash -c "./realestate_frontend_ctl.sh" expose: - 8092 networks: glory1network: ipv4_address: 10.1.1.6 depends_on: - real_estate_master_db - real_estate_tenant1_db realestate_backend: image: realestate_web_backend_service container_name: realestate_backend_con restart: "always" build: ./backend command: bash -c "./realestate_backend_ctl.sh" expose: - 8091 volumes: - static_volume:/home/inara/RealEstatePreProd/static - media_volume:/home/inara/RealEstatePreProd/media networks: glory1network: ipv4_address: 10.1.1.7 env_file: - "./database/env" depends_on: - realestate_frontend - real_estate_master_db - real_estate_tenant1_db networks: glory1network: external: true volumes: real_estate_master_db_volume: real_estate_tenant1_db_volume: static_volume: media_volume: My nginx configuration file: upstream realestate_frontend_site { server realestate_frontend:8092; } server { listen 8000; access_log /home/inara/RealEstatePreProd/realestate_frontend-access.log; error_log /home/inara/RealEstatePreProd/realestate_frontend-error.log; client_max_body_size 0; location / { proxy_pass http://realestate_frontend_site; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 0; } } upstream realestate_backend_site { server realestate_backend:8091; } server { listen … -
How to use Django signals when has role based decorators?
I 'm trying to add signals when an employer or admin/staff has created a shift. Currently I have a view like this, I 'm wondering how should I modify it so I can have a post-save signal? @login_required @admin_staff_employer_required def createShift(request): user=request.user employer=Employer.objects.all() form = CreateShiftForm() if request.method == 'POST': form = CreateShiftForm(request.POST) if form.is_valid(): form.save() messages.success(request, "The shift has been created") return redirect('/shifts') else: messages.error(request,"Please correct your input field and try again") context = {'form':form} return render(request, 'create_shift.html', context) Thanks for your help! -
"Quickstart: Compose and Django" documentation explanation. What does version refer to?
Hi I'm doing this documentation for docker. and I have to add this code to docker-compose file(step 9) version: '3' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db My question is, this is docker-compose version or docker? My instructor said it must be your docker version but 2.13.0 is the latest docker-compose version and Version 20.10.21 is latest docker version. My docker version is 20.10.17 and my docker-compose version is v2.6.1 what is 3? python version?! -
if number inputted is between 0 - 20000 update products prices [closed]
my company needs dev work and although I am not a dev I can read and write code a bit and have created an awesome capture form to load clients into our database. However I am currently stuck on a requirement. (Some Back ground) I built a django app which has some js functions in the html. We have products which I have made a dropdown in the form with set prices depending on the product selected it will update the field with the prices. ` if (Product.value == "certain cover"){ $('#Do_Premium').val('49'); $('#Premium').val('49');} ` Now there is a requirement to add tiering , say you are a silver member the prices will be lower (silver instead of 49 you will get "39") (Gold instead of 39 you will get "29") and so on. Now the QUESTION when the form loads a client is to put a number in that needs to be linked to a tier ie. 0-20000 Silver 20001 - 400000 Gold and so on . How would I code it so that when the user puts the number in it does a check to see which tier it needs to go use and then update field with that … -
Django xhtml2pdf error - SuspiciousFileOperation
I am implementing xhtml2pdf module for my django app. I have been able to print reports, however I am not getting my static configuration to work. I am getting error SuspiciousFileOperation at /moc-content/165/print-report The joined path (/moc/static/moc/main.css) is located outside of the base path component (/Users/xxx/Documents/django-projects/MOC/env/lib/python3.10/site-packages/django/contrib/admin/static) I have implemented link_callback function as xhtml doc is suggesting, but could not figure it out whats wrong with my settings: # settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'moc/static') STATIC_URL = 'moc/static/' # Media files (uploads) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = 'moc/media/' My xhtml functions are as per official docs My vs code directory tree https://i.stack.imgur.com/FWGuv.png -
Django Template: How to check if a variable is in another variable?
Beginner in Django here , I want to check if a particular string variable is in another variable inside the for loop. a = 'abc' b = 'abcd' I have tried below codes:- {% if a in b %} {% if '{{a}}' in b %} {% if '{{a}}' in '{{b}}' %} But none of them seem to work , can anybody guide me here please ? -
Django Raw SQL not returning expected results
I have the below function - it takes orgid, journalid and pid as url parameters. It SHOULD apply those filters to the journal.objects before running the query. However, it returns everything, even when there is only one record meeting the criteria passed in the URL params, Is there anything obvious that would cause that to happen? Thanks a lot @login_required(login_url='/login/') def viewjournal(request, orgid, journalid, pid): user = request.user journals = journal.objects.filter(orgid=org.objects.get(orgid=orgid), updateid=journalid, projectid=project.objects.get(projectid=pid)).raw(''' SELECT 1 as id, updateid, app_journal.orgid, app_journal.projectid, actions, datetime, epoch, app_project.projeectname FROM app_journal left join app_project on app_project.projectid = app_journal.projectid and app_project.orgid = app_journal.orgid''') return render(request, 'pmjournal.html', {'journals': journals}) -
How to attach foreign key associated with the multiple models to submit one form
How can in create inline formset which share the same foreign key using function base views. I don't want to keep selecting product title(which is the FK to other forms) because am using two forms with linked to one Foreign key# i want to implement this https://www.letscodemore.com/blog/django-inline-formset-factory-with-examples/ in function base views I have these 3 models #product model class Product(models.Model): title = models.CharField(max_length=150) short_description = models.TextField(max_length=100) def __str__(self): return self.title *Image model* class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) image = models.ImageField(blank=True, upload_to='images') def __str__(self): return self.product.title *variant model* class Variant(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE) size = models.CharField(max_length=100) quantity = models.PositiveIntegerField(default=1) price = models.DecimalField(max_digits=12, decimal_places=2) def __str__(self): return self.product.title Forms **Forms** from django import forms from django.forms import inlineformset_factory from .models import ( Product, Image, Variant) class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' widgets = { 'title': forms.TextInput( attrs={ 'class': 'form-control'} ), 'short_description': forms.TextInput( attrs={'class': 'form-control'}), } class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' class VariantForm(forms.ModelForm): class Meta: model = Variant fields = '__all__' widgets = { 'size': forms.TextInput(attrs={'class': 'form-control'} ), 'quantity': forms.NumberInput(attrs={'class': 'form-control'}), 'price': forms.NumberInput(attrs={ 'class': 'form-control'}), } VariantFormSet = inlineformset_factory( Product, Variant, form=VariantForm, extra=1, can_delete=True, can_delete_extra=True ) ImageFormSet = inlineformset_factory( Product, … -
Django ImportError: cannot import name 'Post' from partially initialized module (most likely due to a circular import)
So I have an app tentacle that has a processor.py file which imports some Models. The models.py also imports that function as it is used on a model's save method. Now when migrating I get a circular import error. I already tried these and changed the import from relative to an absolute alike version which didnt help. So how to "mutually" share the models and function inside processor.py and models.py which are located in sibling apps? -
Django Rest Framework Cannot save a model it tells me the date must be a str
I have this Profile model that also has location attached to it but not trying to save the location now only trying to save the Profile but get an error: class Profile(models.Model): # Gender M = 'M' F = 'F' O = 'O' GENDER = [ (M, "male"), (F, "female"), (O, "Other") ] # Basic information background = models.FileField(upload_to=background_to, null=True, blank=True) photo = models.FileField(upload_to=image_to, null=True, blank=True) slug = AutoSlugField(populate_from=['first_name', 'last_name', 'gender']) first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100) birthdate = models.DateField() gender = models.CharField(max_length=1, choices=GENDER, default=None) bio = models.TextField(max_length=5000, null=True, blank=True) languages = ArrayField(models.CharField(max_length=30, null=True, blank=True), null=True, blank=True) # Location information website = models.URLField(max_length=256, null=True, blank=True) # owner information user = models.OneToOneField(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "profile" verbose_name_plural = "profiles" db_table = "user_profiles" def __str__(self): return self.first_name + ' ' + self.last_name def get_absolute_url(self): return self.slug and this is the view I am using to save the Profile with. I tried sending the data to a serializer first and saving that but the serializer was invalid every time: class CreateProfileView(APIView): permission_classes = [permissions.IsAuthenticated] def post(self, request): data = dict(request.data) location = {} location.update(street=data.pop('street')) location.update(additional=data.pop('additional')) location.update(country=data.pop('country')) … -
Django call function to save file cannot work
I am create Django project and create function for download file, But my project cannot work view.py from django.http.response import HttpResponse from django.conf import settings from django.http import HttpResponse, Http404 def index(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'my_file.json' filepath = BASE_DIR + '/filedownload/' + filename download(request,filepath) return HttpResponse('Download File') def download(request, path): file_path = path if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/x-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 How can I solve this? -
Get the first three human readable elements in a queryset
I'm trying to render elements in a Django view. Every clinic object has many specialities, but for estetic reasons I only want the first three of them to be displayed in the template. I've tried: def clinics_index(request): clinics = Clinic.objects.all() for clinic in clinics: speciality = clinic.get_speciality_display context = { 'clinics' : clinics, 'speciality' : speciality.first, } return render(request, 'guide/clinic/clinic_directory.html', context) This now renders the human-readable name of the speciality field (which is a multiple choice field in the model). However, I can't use substraction to only get 3 elements like here: speciality = clinic.get_speciality_display[:3] As I get the following error: TypeError at /guide/clinics/ 'method' object is not subscriptable How can I render it? -
No module named 'graphql.type' in Django
I am New in Django and GraphQL, following the the article, I am using python 3.8 in virtual env and 3.10 in windows, but same error occurs on both side, also tried the this Question, i also heard that GraphQL generate queries, But dont know how to generate it, But this error occurs: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/talha/ve/lib/python3.8/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/home/talha/ve/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/talha/ve/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/talha/ve/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/talha/ve/lib/python3.8/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
How to Change the Format of a DateTimeField Object when it is Displayed in HTML through Ajax?
models.py class Log(models.Model): source = models.CharField(max_length=1000, default='') date = models.DateTimeField(default=datetime.now, blank = True) views.py The objects in the Log model are filtered so that only those with source names that match a specific account name are considered. The values of these valid objects will then be listed and returned using a JsonResponse. def backlog_list(request): account_name = request.POST['account_name'] access_log = Log.objects.filter(source=account_name) return JsonResponse({"access_log":list(access_log.values())}) dashboard.html This Ajax script is the one that brings back the account name to the views.py. If there are no valid objects, the HTML will be empty; however, it will display it like this otherwise. <h3>You scanned the QR code during these times.</h3> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'POST', url : "/backlog_list", data:{ account_name:$('#account_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(response){ console.log(response); $("#display").empty(); for (var key in response.access_log) { var temp="<div class='container darker'><span class='time-left'>"+response.access_log[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occurred') } }); },1000); }) </script> My goal is to have the Date and time displayed like "Jan. 10, 2000, 9:30:20 A.M." I've tried changing the format directly from the models.py by adding "strftime" but the error response is triggered.