Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'NoneType' object has no attribute 'id' error in AutoField table
I have this models.py class Departamento(models.Model): id = models.AutoField(db_column='ID', primary_key=True) nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True) class Utilizador(AbstractBaseUser): id = models.AutoField(db_column='ID', primary_key=True) departamentoid = models.ForeignKey(Departamento, models.DO_NOTHING, db_column='DepartamentoID', blank=True, null=True) email = models.CharField(db_column='Email', max_length=255, blank=True, null=True, unique=True) nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' And in my view I am doing utilizador = Utilizador.objects.get(request.user.id) dep = Departamento.objects.get(id=utilizador.departamentoid.id) I am using this view in a template but I cant render the template because of this error "'NoneType' object has no attribute 'id'" Why is this happening? -
How to display messages in a chat application in Django
I am building a chat application in Django. But I am confused about how to show messages as soon as the person on the other side sends a message. At present, I have to reload the page to view the messages. I thought of refreshing the page automatically for 3-5 seconds. Is there any way to display messages as soon as the other person sends a message -
Django AUTH_PASSWORD_VALIDATORS for password not working in BaseManager class
I want to validate the password with a min length of 9 and I specified it in AUTH_PASSWORD_VALIDATORS as: { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, I use Django serializer to serializer the request: class UserSerializer(serializers.ModelSerializer): date_joined = serializers.ReadOnlyField() user_type = serializers.ListField(child=serializers.CharField(max_length = 20)) class Meta(object): model = User fields = ('id', 'email', 'first_name', 'middle_name', 'last_name', 'mobile_num', 'date_joined', 'password','user_type', 'otp_verified') id = serializers.CharField(max_length=10) email = serializers.EmailField() password = serializers.CharField(style={'input_type': 'password'}) extra_kwargs = {'password': {'write_only': True}} Here I want to check for password validation in BaseManager and coded accordingly: class UserManager(BaseUserManager): def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') try: with transaction.atomic(): user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user except: raise def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) if(len(password) < 9): raise ValidationError("length too short") else: return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) return self._create_user(email, password=password, **extra_fields) def get_default_password_validators(self, password): return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) now = datetime.datetime.now() class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) middle_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=now) user_type = ArrayField(models.CharField(max_length = 20)) mobile_num = models.CharField(max_length = 10) otp_verified = models.BooleanField(default=False) objects = UserManager() In … -
Adding additional meta data to django apps.py and accessing it from other apps
I would like to add additional meta data to the apps.py which I can use the same way as "name" and "verbose_name". In particular this would allow me to create an app which displays information about other installed apps. The following approach does not seem to work: App no1: #apps.py / myapp class MyappConfig(AppConfig): name = "myapp" verbose_name = "My app" description = "whatever description i would like to add" App no2: #model.py / differentapp apps.get_app_config("myapp").verbose_name # Works apps.get_app_config("myapp").description # Fails Is there a way to make this work? If not what would be a suitable approach to achive this goal? Thank you for your help! -
ModuleNotFoundError: No module named Again
I just creating a simple backend and everything working fine until I create this python filepopulate_fake_script.py when I'm trying to run this it's showing ModuleNotFoundError: No module named And I've already checked other similar questions but unable to solve. Please help me to fix this. And you can see all files in here https://github.com/crajygemer/Django_Stuff/tree/master/ten_project import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ten_project.settings') import django django.setup() # Fake Pop Script import random from ten_project.ten_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] # call Topic Model def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t # call rest of Models def populate(N=5): for entry in range(N): # get the topic for the entry top = add_topic() # add fake data for each entry fake_url = fakegen.url() fake_name = fakegen.company() fake_date = fakegen.date() # fake entry for webpage model webpg = Webpage.objects.get_or_create( topics, url=fake_url, name=fake_name)[0] # fake entry for access record acc_rec = AccessRecord.objects.get_or_create( name=webpg, date=fake_date)[0] if __name__ == '__main__': print('Run Fake Script') populate(20) print('Run Successfully.') -
How can I create custom ID in django?
As Far I know, we can create a custom ID using UUIDField(). id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) But how can I change the ID that would look like AAYYMMDDNNNN Where, ⦁ First 2 characters - 'AA' ⦁ YY - Capture year on which its registered ⦁ MM - Capture month on which its registered ⦁ DD - Capture current date on which its registered ⦁ NNNN - Random number based on the every day new set of NNNN will be generated (0001 - 9999) -
not installed requirements.txt on django project
I am new to programming and this is my first project trying to start a django project on the server activated virtual environment after the pip install -r requirements.txt command, an error occurs Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 353, in run wb.build(autobuilding=True) File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepa re_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 554, in _prep are_file require_hashes File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 278, in p opulate_link self.link = finder.find_requirement(self, upgrade) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 465, in find_requir ement all_candidates = self.find_all_candidates(req.name) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 423, in find_all_ca ndidates for page in self._get_pages(url_locations, project_name): File "/usr/lib/python2.7/dist-packages/pip/index.py", line 568, in _get_pages page = self._get_page(location) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 795, in get_page resp.raise_for_status() File "/usr/share/python-wheels/requests-2.18.4-py2.py3-none-any.whl/requests/m odels.py", line 935, in raise_for_status raise HTTPError(http_error_msg, response=self) HTTPError: 404 Client Error: Not Found for url: https://pypi.org/simple/beatiful lsoup4/ -
Trying to call an API with an image but keeps getting ValueError
I have been following the advice given on this thread: How to pass image to requests.post in python? However, I got stuck with the error, "ValueError: read of closed file". I have been trying to invoke an API that does some image recognition. At the moment, I am using Postman's form-data feature to send it to the Django server, which then uses "requests" to invoke the API. Let me show you the code snippet. def post(self, request): img = request.FILES['file'] with img.open('rb') as f: files = {'fileToUpload': f} url = 'http://XXXXXXXXXXXXXXXX/getSimilarProducts?APIKEY=XXXXXXX' response = requests.post(url, files=files) After sending the request, when I check each variable with the debugger, the 'img' variable contains a temporary uploaded file like so: <TemporaryUploadedFile: XXXXXXXXXXXXXX.png (image/png)> What am I missing? And what should I do to overcome this error? Thanks a lot in advance! -
Make a binary tree index on ArrayField of Django with Postgresql
I have two models that one of them has an ArrayField of another one, the code is like this: class ModelA(models.Model): created_at = models.DateTimeField(default=timezone.now) other_fields... class ModelB(models.Model): list_of_a = ArrayField(ModelA(), size=31, default=list) other_fields... What I want is that list_of_a has a B-tree index such that instances of ModelA with less created_at value be on top of it. Is this possible? -
AttributeError at /order 'OrderClass' object has no attribute 'item' in for loop inside views
I cannot find a solution to this problem. I am new to Django and I am creating a web app where I have this models file class CardItem(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name="cart") addons = models.TextField(blank=True) toppings = models.TextField(blank=True) def __str__(self): return f"{self.user} - {self.item} {self.addons} {self.toppings}" class Status(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return f"{self.name}: {self.description}" class OrderClass(models.Model): plates = models.ManyToManyField(CardItem) status = models.ForeignKey(Status, on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places = 2) def __str__(self): return f"{self.item} Status: {self.status}" And in my views file: def order(request): if request.method == 'POST': items = CardItem.objects.filter(user = request.user) price = request.POST.get("totalPrice") new_order = OrderClass() new_order.price = price for i in items: top = request.POST.getlist(str(i.id) + "topping") add = request.POST.getlist(str(i.id) + "addon") i.toppings = str(top) i.addons = str(add) i.save() print(i) new_order.plates.add(i) The i.save() is working and when I print the i, I get a CardItem, however, in new_orde.plates.add(i) I get this error: AttributeError at /order 'OrderClass' object has no attribute 'item' Traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/order Django Version: 3.0.7 Python Version: 3.8.2 Installed Applications: ['orders.apps.OrdersConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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 (most recent … -
No module named 'oauth2_provider.ext'
i'm having this error could someone help me with it. File "/Users/king/Desktop/dash1-env/DASH/lib/python3.7/site-packages/rest_framework_social_oauth2/views.py", line 7, in from oauth2_provider.ext.rest_framework import OAuth2Authentication ModuleNotFoundError: No module named 'oauth2_provider.ext' -
400 Client Error: Bad request for url; Using requests to exchange Discord access token
I was setting up a site, and the user should be able to log in with Discord but there's a problem. So there's a login button which sends them to the proper Discord link, authorizes the user, and sends an access token back to the redirect which is a link on my site. The site grabs the code and should exchange it for user info. The problem is with exchanging the token. I'm getting an error that I've no idea how to fix, I even tried copying the code example on the Discord docs, and I still get the error. The code is below, if you need anymore of my code then I'll gladly edit it into the post. P.S. the site is made using Django. def exchange_code(code): API_ENDPOINT = 'https://discord.com/api/v6' CLIENT_ID = 'client_id' CLIENT_SECRET = 'client_secret' REDIRECT_URI = 'http://localhost:8000' data = { 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': REDIRECT_URI, 'scope': 'identify email connections' } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers) r.raise_for_status() return r.json() -
Django running on Postgre extremely slow on only 100 data
Recently I added 100 fake data to one of my models in Django, however, now the age is taking forever, to load. for getting Post objects in my view I do: posts = Post.objects.select_related('author').all().order_by('-last_edited') my Post model is: class Post(models.Model): title = models.CharField(max_length=100) guid_url = models.CharField(max_length=255,unique=True, null=True) content = models.TextField(validators=[MaxLengthValidator(1200)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) last_edited= models.DateTimeField(auto_now=True) tags = TaggableManager(help_text="Tags", blank=True) likes= models.ManyToManyField(Profile, blank=True, related_name='post_likes') I am using Postgre SQL as my database but I do not know what's causing this issue. Since I believe 100 data should be easily handled. Can it be because of something in my template? Now inside my template (It is very long so I do not want the question to get messy) I have for instance liking the post, images, ... ) But I am not doing any heavy queries inside the template. -
How to use Django AUTH_PASSWORD_VALIDATORS in UserMagaer with custom valiadtoion?
I want to register a user with django User class, email validation is happening but for password I use the django password validations like MinimumLengthValidator, CommonPasswordValidator and tried using it in models.py but it seems only email valdation happens and password validation goes wrong. I am a beginner in django password authetication class. So can anyone tell me where should I put the code on password authetication, serializer.py or models.py? Please correct me. AUTH_USER_MODEL = 'users.User AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] This is my setting.py from rest_framework import serializers from.models import User`` class UserSerializer(serializers.ModelSerializer): date_joined = serializers.ReadOnlyField() user_type = serializers.ListField(child=serializers.CharField(max_length = 20)) class Meta(object): model = User fields = ('id', 'email', 'first_name', 'middle_name', 'last_name', 'mobile_num', 'date_joined', 'password','user_type', 'otp_verified') id = serializers.CharField(max_length=10) email = serializers.EmailField() password = serializers.CharField(style={'input_type': 'password'}) extra_kwargs = {'password': {'write_only': True}} I am using serializer.py file and calls User model from __future__ import unicode_literals from django.db import models from django.contrib.postgres.fields import ArrayField from django.utils.timezone import utc from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin, BaseUserManager ) import datetime import django.contrib.auth.password_validation as … -
Use sendgrid template instead of django-alluth template when confirming email
I used django cookiecutter to initialize my project. I am using sendgrid_backend.SendgridBackend as my email backend. I can send emails now with sendgrid but I would like to use my sendgrid template instead of the template provided by django allauth. Here is the adapters.py provided by allauth from typing import Any from allauth.account.adapter import DefaultAccountAdapter from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from django.conf import settings from django.http import HttpRequest class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request: HttpRequest): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) class SocialAccountAdapter(DefaultSocialAccountAdapter): def is_open_for_signup(self, request: HttpRequest, sociallogin: Any): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) -
django.utils.translation does not translate but python import gettext does
I am using django 2.2, I have been tasked to make a site multi lingual supported. My development environment is Windows 10. I have installed gettext by downloading the binaries and xgettext --version gives me xgettext (GNU gettext-tools) 0.20.2 Copyright (C) 1995-2020 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Written by Ulrich Drepper. so I know get text is working. My settings file is having the following LANGUAGE_CODE = 'de' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True from os import path LOCALE_PATHS = ( path.join(path.abspath(path.dirname(__file__)), 'locale'), ) I have just put "de" for testing. I have run makemessages -l de and compilemessages. I have the ".po" , ".mo" files as well. In my views and in my templates , translations do not see to work. i.e. from django.utils.translation import ugettext as _ from django.utils import translation output = _('StatusMsg') hello = _("hello") print(output) return render(request, 'polls/index.html',{'hello':hello, 'status':output}) my template code is {% load i18n %} <html> <head> </head> <body> <h1> {% trans 'Welcomeheading' %} </h1> <p> {% … -
Django Update any user account
I'm trying to create a function where an admin would be able select a user and update his/her profile he likes.But whenever i try to update a user I get this error "Profile with this User already exists" . views.py def customer_profile(request,pk): profile = Profile.objects.get(id=pk) form = UpdateUserProfileForm(request.POST,instance=profile) if request.method == 'POST': if form.is_valid(): instance= form.save(commit=False) instance.save() context = { 'form':form } return render(request, "customerprofile.html", context) forms.py class UpdateUserProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) address = models.CharField(max_length=100) phone = models.IntegerField() image = models.ImageField(default='default.jpg', null=True) def __str__(self): return f'{self.user.username} Profile' -
Django Dynamic Form Field - how to change?
In my Django form below class Form_Vechicle(forms.ModelForm): flatno_id = forms.ModelChoiceField(widget=forms.Select( attrs={'class': 'form-control form-control-sm'}), required=True, help_text="Select flat No from the list", empty_label="Select flat no", queryset=FlatNo.objects.filter(is_deleted=False).order_by("flatindex"), label="Flat No") reg_no = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control form-control-sm'}), required=True, min_length=2, max_length=15, help_text="Regtration No", label="Veh No") detail = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control form-control-sm'}), required=True, max_length=25, help_text="make/modal", label="Brand") class Meta: model = Vehicle fields = ['flatno_id', 'reg_no', 'detail' ] how do I change form field widget dynamically based on user login type No change in this form if user is superuser. For all other user (non superuser), I would like to hide the flatno_id field flatno_id = widgets.HiddenInput() Any help on this would be much appreciated. Thanks a lot in advance. -
How to add attribute to instance variables in a python class
To keep this simple, in my Django/Python sports pool application, each user is creating their own pool. Therefore, in the Pool class, I need to make all the class variables be instance variables so no user is changing values on another users Pool class instance. a quick sample of code in the models.py file would be .... ''' class Pool(models.Model): def init(self, team_name): self.team_name = team_name ''' What if I wanted to add attributes to the team_name field such as max_length = 100 or unique=True I understand the instance variables values must be passed to the class upon instantiation, so is it that the value being passed must already be defined with those attributes? How do I handle this. Thanks! p.s. My apologies if I screwed up the formatting of this question. I'm having challenges with inserting code. Sorry! -
How to use a different domain for Djoser email?
How can I change the domain the link inside the email djoser sends uses? -
Django - Send JSON with Image to Server
I have a model - class Store(models.Model): store_id = models.AutoField(primary_key=True) owner = models.ForeignKey(CustomUser, on_delete = models.CASCADE) name = models.CharField(max_length=75) description = models.TextField(blank=True) logo = models.ImageField(upload_to='store/') contactNumber = PhoneNumberField(blank=True, help_text='Contact number') start = models.TimeField(auto_now=False, auto_now_add=False) end = models.TimeField(auto_now=False, auto_now_add=False) sundayOpen = models.BooleanField(default=False) mondayOpen = models.BooleanField(default=False) tuesdayOpen = models.BooleanField(default=False) wednesdayOpen = models.BooleanField(default=False) thursdayOpen = models.BooleanField(default=False) fridayOpen = models.BooleanField(default=False) saturdayOpen = models.BooleanField(default=False) I have a serializer that can take image field without a couple of fields (which I set myself - the store ID and the owner) class CreateStoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = ('name','description','logo','contactNumber', 'start','end','sundayOpen','mondayOpen','tuesdayOpen','wednesdayOpen', 'thursdayOpen','fridayOpen','saturdayOpen') I have a view that should handle the request - Image + JSON class StoreDetailView(APIView): def post(self, request,store_id=None): objj = CreateStoreSerializer(data=request.data) print(objj.is_valid()) return Response(status=status.HTTP_200_OK) The serializer validation says its invalid. I tried sending a request from Postman with JSON data except the image field in it. The image field was chosen with form-data with the same name as the imageField (logo) I put the Content-Typeas application/json. However, serializer validation says false. How do I fix this? -
Block Django Urls to Users
I'm new to django and making a project on django and react React has all the frontend code and django has all the REST api. I am using axios to make GET or POST request. The django urls has views to save the data or retrieve the data. Now the problem is, I do not want the user to access the django urls, they must be used only by axios. For example: If this is my url path(r'^contactform/contact/',ContactView.as_view()) and you visit it on browser http://localhost:8000/contactform/contact/ it shows a django-rest-framework's ListCreateAPIView as I used it. I want to redirect user to a template or show an error page. -
Docker Compose: could not connect to server
Literally pulling my hair out trying to get this to work. In Dockerfile: FROM python ENV PYTHONUNBUFFERED 1 RUN mkdir /my_project WORKDIR /my_project # requirements.txt is also in the current directory which includes Django and psycopg2 COPY . /my_project RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate In docker-compose.yml: version: "3.8" services: my_db: container_name: my_db image: postgres environment: - POSTGRES_DB=db1 - POSTGRES_USER=postgres - POSTGRES_PASSWORD=123456 volumes: - my_db_volume:/my_project web_app: container_name: web_app build: . command: python manage.py runserver volumes: - web_app_volume:/my_project ports: - "8000:8000" depends_on: - my_db volumes: my_db_volume: web_app_volume: In settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "db1", "USER": "postgres", "PASSWORD": "753951456852", "HOST": "my_db", "PORT": "5432", } When I run docker-compose up, I get the following error: (venv) C:\Users\super\Desktop\GitHub\project> docker-compose up Creating volume "arbormetrixassessmentjackwu_my_db_volume" with default driver Creating volume "arbormetrixassessmentjackwu_web_app_volume" with default driver Recreating my_db ... done Recreating web_app ... done Attaching to my_db, web_app my_db | my_db | PostgreSQL Database directory appears to contain a database; Skipping in itialization my_db | my_db | 2020-06-26 01:06:30.907 UTC [1] LOG: starting PostgreSQL 12.3 (Debian 1 2.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-b it my_db | 2020-06-26 01:06:30.909 UTC [1] LOG: listening on … -
How to remove character "T" in a DateTimeField in Django Vue.js?
I have a list with comments, those comments have a moment field, wich is a DateTimeField, in this DateTimeField I have for example this --> 2020-06-03T15:32:01.803027 and I want to delete that T character, or replace with a blank space. I'm using Django for the backend and Vue.js for the frontend. I was able to remove the Z character by changing the USE_TZ = True to False option in the settings.py file. But I can't remove the T character, that's all I need. I have tried from the frontend to remove the T character using methods and computed properties, but I can't use the replace("T", " ") method on a DateTimeField, I can only use it on a String <div class="container"> <div class="row"> <div class="col text-left"> <h2>Detalles del partido</h2> </div> </div> <div class="row"> <div class="col"> <div class="card"> <div class="card-body"> <form> <form @submit="onSubmit"> <div class="form-group row"> <label for="nombreLocal" class="col-sm-2 col-form-label">Local</label> <div class="col-sm-6"> <input type="text" name="nombreLocal" class="form-control" readonly v-model.trim="form.nombreLocal"> </div> </div> <div class="form-group row"> <label for="nombreVisitante" class="col-sm-2 col-form-label">Visitante</label> <div class="col-sm-6"> <input type="text" name="nombreVisitante" class="form-control" readonly v-model.trim="form.nombreVisitante"> </div> </div> <div class="form-group row"> <label for="resultado" class="col-sm-2 col-form-label">Resultado</label> <div class="col-sm-6"> <input type="text" name="resultado" class="form-control" readonly v-model.trim="form.resultado"> </div> </div> <div class="form-group row"> <label for="pronosticoSistema" class="col-sm-2 col-form-label">Pronóstico … -
Django project, pure javascript, html and template tags best practices
I am new to developing a website and because of my familiarity with Python and considering the complexity of the website, I chose Django. I want to know the best practice for developing a template through the Django framework. My question is two-fold. Is it best to have a bunch of for loops / if statements in the template using template tags and other features of Django? Or is it passing the variables from Django to Javascript through JSON and then loading the page asynchronously? For the first, I found the following merits: its fairly easy. I know what I want, I code the loops and I get the result that I expect. Plus giving IDs / names to HTML tags is super simple. Inline scripting also becomes simple, but I personally dont like it. But as objects start to get high in number, page load speed suffers. For the second, and I am very new to this, the ease is gone. There is, I feel, another hoop to jump through Javascript, with JSON parsing and then the actual modeling. If not either first or second, may be there is a balance between the two? All help is appreciated.