Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OperationalError at /admin/app1/coursemodel/ no such column: app1_coursemodel.money
i tried to add a new field to already existing model and this is being displayed. class CourseModel(models.Model): cname = models.CharField(max_length=15) dur = models.IntegerField() fee = models.IntegerField() money = models.IntegerField() --- this is what is added I tried python makemigrations whc=ich is giving the follwing error: You are trying to add a non-nullable field 'money' to coursemodel without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models. -
Django request.session don't save data
I'm trying to retrieve the session data after login but it doesn't seem to be saving the information . class getSession(View): def post(self, request): print('====================>') print(request.session.get('usuario')) sesion = request.session.get('usuario') return JsonResponse({'nombre': sesion.nombre, 'rut':sesion.rut}) class Login(View): def post(self, request): data = json.loads(request.body) try: usuario = Usuario.objects.get(rut=data['rut'], password=data['password']) request.session['usuario'] = {'nombre': usuario.idpersona.name, 'rut': usuario.rut} request.session.modified = True #print(self.request.session['usuario']) return JsonResponse({'usuario':usuario.rut}) except: return JsonResponse({'usuario':'no existe'}) I'm get this error. AttributeError: 'NoneType' object has no attribute 'nombre' I'am using fetch with react. async login() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rut: this.state.rut, password: this.state.password, }), }; const response = await fetch("http://127.0.0.1:8000/test", requestOptions); const data = await response.json(); if (data.usuario == "no existe") { mensajeError("RUT o contraseña inválidos."); } else { mensajeExitoso("Usuario validado correctamente."); setTimeout(() => { window.location.href = "/Inicio"; }, 2000); } console.log(data.usuario); } try setting SESSION_SAVE_EVERY_REQUEST = True in settings.py -
How to programatically run custom command for specific schema using django-tenants?
I am new with django-tenants. I want to programatically run a cummand I have created with management.call_command() but I am getting error. Can someone help me with this? This command runs without error. I want to achieve same programatically. python manage.py tenant_command load_some_data --schema=<schema_name> my code: call_command('tenant_command', 'load_user_groups', schema_name=schema_name) I get following error: File "/home/stackuser/Desktop/DjangoPr/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 114, in call_command app_name = get_commands()[command_name] TypeError: unhashable type: 'list' -
Purpose of using an API
I'm learning API. So, I have a Django app, in development (I'm building it).I can also render my data (or user's data POST through forms) with urls.py, views.py and my template files. When runserver with localhost. I can GET,POST any data through processing some kind of forms and render it. So my question is, when my app is in production, should I need to write an API to GET,POST data. Here is my processing of views.py ` @login_required(login_url="login") def createProject(request): profile = request.user.profile form = ProjectForm() if request.method == "POST": form = ProjectForm(request.POST, request.FILES) if form.is_valid(): project = form.save(commit=False) project.owner = profile project.save() return redirect("account") context = {"form": form} return render(request, "projects/project_form.html", context) ` What's wrong with my thinking. Could u help me! Thanks -
How can I do this complex Django queryset correctly?
Let's say I have these three models: class Author(models.Model): name = models.CharField(max_length=64) class Book(models.Model): author = models.ForeignKey( Author, blank=True, null=True, on_delete=models.SET_NULL ) name = models.CharField(max_length=64) class Store(models.Model): books = models.ManyToManyField(Book) name = models.CharField(max_length=64) I don't know the author of some books. In these cases, the author is null. When I query Store, I would like to know how many books each store has and sort them. So my queryset is something like this: Store.objects.all().annotate(books_count=Count('books')).order_by('-books_count') Now, what if I want to count only the books that have an author? I tried this queryset, but it is clearly not correct: filter = Q(books__author__isnull=False) Store.objects.annotate(books_count=Count(filter)).all().order_by('-books_count') Does anyone know the correct way to do this query? -
Forbidden (403) CSRF verification failed. Request aborted-Real time chat application with Django Channels
I'm doing a course from YouTube "Python Django Realtime Chat Project - Full Course" and I'm new to django.My problem is, When I try to send message in room chat (submit form) I get this error Forbidden (403) CSRF verification failed. We don't have CSRFtoken in our form in room.html but The instructor fixed the error by adding e.preventDefault(); and return false; in submit querySelector block in room.html. I still get the error. when submitting the form message should add to div with chat-messages id. room.html: {% extends 'core/base.html' %} {% block title %} {{room.name}} {% endblock %} {% block content %} <div class="p-10 lg:p-20 text-center"> <h1 class="text-3xl lg:text-6xl text-white">{{room.name}}</h1> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id="chat-messages"> <div class="p-4 bg-gray-200 rounded-xl"> <p class="font-semibold">Username</p> <p>Message.</p> </div> </div> </div> <div class="lg:w-2/4 mx-4 lg:mx-auto p-4 bg-white rounded-xl"> <form method='POST' action='.' class='flex'> <input type="text" name="content" class="flex-1 mr-3" placeholder="Your message..." id="chat-message-input"> <button class="px-5 py-3 rounded-xl text-white bg-teal-600 hover:bg-teal-700" id="chat-message-submit"> send </button> </form> </div> {% endblock %} {% block script %} {{room.slug|json_script:"json-roomname"}} {{request.user.username|json_script:"json-username"}} <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const userName = JSON.parse(document.getElementById('json-username').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e) { … -
Is it possible to prefetch model with one query in this case?
Is it possible to prefetch Models B to Model A with one query or with minimal queries. I'm confused. Thanks. from django.db import models class ModelA(models.Model): pass class ModelB(models.Model): pass class ModelC(models.Model): model_a = models.ForeignKey(ModelA, related_name="models_a", on_delete=models.CASCADE) models_b = models.ManyToMany(ModelB, through="ModelD") class ModelD(models.Model): model_c = models.ForeignKey(ModelC, on_delete=models.CASCADE) model_b = models.ForeignKey(ModelB, on_delete=models.CASCADE) I'm do something like that, and it is work. But seems a bit ugly. models_a_list = ModelsA.objects.all() model_d_qs = ModelD.objects.select_related("model_c", "model_b") model_d_map = defaultdict(list) for d_item in model_d_qs: model_d_map[d_item.model_c.model_a.id].append(d_item.model_b) for a_item in models_a_list: settatr(a_item, "model_b_set", model_d_map.get(a_item.id)) return models_a_list -
How to convert Polygon object in Django GIS to an image
I am running a Django project, I created a Company model with company_activity_area field. My goal is to generate an image from the map. and even better, to generate a map image for each polygon. this is my code. from django.contrib.gis.db import models class Company(models.Model): company_activity_area = models.MultiPolygonField(null=True, blank=True, srid=4326, verbose_name='Area of Operation') def save(self, *args, **kwargs): for polygon in self.company_activity_area: # TODO: generate the map image for each polygon, where the polygon appear at the middle of the map super(Company, self).save(*args, **kwargs) -
How to get "starred mails" from Gmail or other mail services using IMAP_tools in django
I am able to get inbox emails and also able to get emails from specific folder but i am unable to get "starred" emails. I tried below code. and i am expecting emails with "starred flag" in response. from imap_tools import MailBox, A # Create your views here. def temp(request): #Get date, subject and body len of all emails from INBOX folder with MailBox('smtp.gmail.com').login('admin@gmail.com', 'password', 'INBOX') as mailbox: temp="empty" for msg in mailbox.fetch(): temp = (msg.date, msg.subject, msg.html) return HttpResponse(temp) -
How to import external .json file to Django database(sqlite)?
So, what is the basic thing I can do to initialize my Django database with the data I have in external .json file. I tried to upload through admin's page after running py manaeg.py runserver but there is no import options. -
Hide modal after form successful submition
I'm using Bootstrap Modals and HTMX to create an event in Django. I got the form rendering OK inside the modal, but when I submit the form the index page appears inside the modal (the success_url parameter of the CreateView). I'd like to hide the modal after the submission and then show the index full screen. This is the modal in the template: <!-- Start modal --> <button type="button" hx-get="{% url 'events:create' %}" hx-target="#eventdialog" class="btn btn-primary"> Add an event </button> <div id="eventmodal" class="modal fade" tabindex="-1"> <div id="eventdialog" class="modal-dialog" hx-target="this"> </div> </div> <!-- End modal --> And this is the Javascript that makes it show the modal: ;(function(){ const modal = new bootstrap.Modal(document.getElementById('eventmodal')) htmx.on('htmx:afterSwap', (e) => { if (e.detail.target.id == "eventdialog") modal.show() }) I tried adding this to the Javascript code but it doesn't work: htmx.on('htmx:beforeSwap', (e) => { if (e.detail.target.id == 'eventdialog' && !e.detail.xhr.response) modal.hide() }) How can I make the modal hide after submitting the form? This is my view: class CreateEvent(LoginRequiredMixin, CreateView): model = Event form_class = EventForm template_name = 'events/events_form.html' success_url = reverse_lazy('events:index') def form_valid(self, form): form.instance.author = self.request.user event_obj = form.save(commit=True) image = self.request.FILES.get('image') if image: EventImage.objects.create(title=event_obj.title, image=image, event=event_obj) return super(CreateEvent, self).form_valid(form) -
I want different authentication system for user and admin in djagno
I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page. def userlogin(request): error = "" if request.method == 'POST': u = request.POST['emailid'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user: login(request, user) error = "no" return redirect(profile) else: error = "yes" except: error = "yes" return render(request, 'login.html', locals()) def login_admin(request): error = "" if request.method == 'POST': u = request.POST['uname'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user.is_staff: login(request, user) error = "no" else: error ="yes" except: error = "yes" return render(request,'login_admin.html', locals()) I want to achive different authentication system for user and also for admin. -
URL with parameters does not find static files Django
I'm making a URL with parameters but it does not find the static files because it adds the name of the URL to the location of the static files, with normal urls this does not happen (I already have some pages working like this). This is a url without parameters This is a url with parameters Look that add 'validador' to static file urls This is the function URLs file -
Django ORM ignoring globally related_name
I have a project with more than 100 models generated from PostgreSQL, when I use it there are many Reverse accessor clashes with ForiegnKey and ManyToManyFields. How can we ignore this functionality of Django globally, instead of adding related_name="+" for each model? -
Django rest Ecommerce category and product offers
I'm trying to acheive catgeory and product offers in my project and am unable to come up with a solution. Like if i give offer to a category all products price in category should get the offer and for products its individual. class Category(models.Model): category_name = models.CharField(max_length=15, unique=True) slug = models.SlugField(max_length=100, unique=True) class Meta: verbose_name_plural = "Category" class Products(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=500) price = models.IntegerField() images = models.ImageField(upload_to="photos/products") images_two = models.ImageField(upload_to="photos/products") images_three = models.ImageField(upload_to="photos/products") stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Products" def __str__(self): return self.product_name class CategoryOffer(models.Model): category = models.OneToOneField(Category, on_delete=models.CASCADE, related_name='cat_offer') valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(100)] ) is_active = models.BooleanField(default=False) def __str__(self): return self.category.category_name class ProductOffer(models.Model): product = models.OneToOneField(Products, on_delete=models.CASCADE, related_name='pro_offer') valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(100)] ) is_active = models.BooleanField(default=False) def __str__(self): return self.product.product_name So above are my models. I don't know how to implement, thought of many ways but it keeps leading to errors. -
Django pressing browser back button causes data to reappear
When a user adds a comment to a post, and they want to go back to the home page, and if they press the browser back button, the form cycles through every time the form had data that they had posted. The user has to press the back button (depending on the amount of comments made) at least 2 or 3 times to get to the home page. For Example: A user adds 1 comment to a form, they press the browser back button and the data that they just submitted appears and has to press the browser back button again A user adds 2 comments to a post, and they press the browser back button and they are on the same page with the last form submission data. They press the browser back button again and they are on the first form submission data. And so on.... I know that we can use a redirect call to the same or different page, but the comments need to update once submitted, and even then the data is still cached. Is there a way to have the user press the browser back button once and it will bring them back to … -
CSRF verification failed when used csrf_token and CSRF_TRUSTED_ORIGINS
I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS. Here is my models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) avatar = models.ImageField(default='static/images/default.jpg', upload_to='static/images') @classmethod def create(cls, authenticated_user): profile = cls(user=authenticated_user, name= authenticated_user) # do something with the book return profile def __str__(self): return self.user.username My view: @login_required def profile(request): """Show profile""" # profile = UserProfile.objects.get(id= request.user) profile = UserProfile.objects.get(user=request.user) if request.method != 'POST': # No data submitted; create a blank form. form = UserProfileForm(instance=profile) else: # POST data submitted; process data. form = UserProfileForm(instance=profile, data= request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('base:index')) context = {'profile': profile} return render(request, 'users/profile.html', context) My template: {% if user.is_authenticated %} <p>Thong tin nguoi dung:</p> <a>Ten nguoi dung: {{profile.name}}</a> <p>Anh dai dien: <img src="{{profile.avatar.url}}" alt=""></p> <form action="{% url 'users:profile'%}" method="post"> {% csrf_token %} <input type="hidden" name="csrfmiddlewaretoken"> <p> <label for="id_name">Name:</label> <input type="text" name="name" maxlength="200" required="" id="id_name"> </p> <p> <label for="id_avatar">Avatar:</label> <input type="file" name="avatar" accept="image/*" id="id_avatar"> </p> <button name="submit">save changes</button> </form> {% else %} {% endif %} How can i sumit my form ? -
How can I save the username in the database as an email?
I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much! enter code here models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views.py class ActivateAccount(View): def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) messages.success(request, ('Your account have been confirmed.')) return redirect('login') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('login') token.py from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Enter a valid email address') class Meta: model = User fields = [ 'password1', 'password2', ] -
Django App Engine deployment stops responding after 5 or 6 requests
I have been fighting this for a while now. Setup: I have Django 4 application running on Google App Engine (Standard) connected to Cloud SQL. Issue: I will load a page, and either refresh it 5 (ish) times or load 5 (ish) different pages. Then the application just stops responding. Observations: No errors are thrown. I have looked at the metrics and it doesn't appear anything is off. When I go to the instances page, they say they are "restarting" but they just are frozen there for many many minutes. Things I have tried: Manual, Basic, and Automatic Scaling Warmup requests Larger instance sizes Higher scaling thresholds Non-zero min instance sizes None of these items have changed the number of requests it takes to freeze the server. I have run the same server locally and it does not stop responding. Thanks people you make the world go round! -
Integrity error raised while creating custom id in django model
I tried to create auto incrementing custom id using the below code in models.py ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import User from django.db.models import Max # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') def save(self, **kwargs): if not self.id: max = bug.objects.aggregate(id_max=Max('id'))['id_max'] self.id = "{}{:03d}".format('BUG', int(max[3:]) if int(max[3:]) is not None else 1) super().save(*kwargs) While adding a record the below error is shown. IntegrityError at /upload/ null value in column "created_at" violates not-null constraint DETAIL: Failing row contains (BUG009, test21, Fixed, test21, +919999999999, 1, null, 2022-11-18 13:55:09.68181+00, pics/between_operation_02WVLVz.png, test21). Tried to generate custom for the model such as BUG001, BUG002 etc. Can anyone give a suitable solution? -
Get the last record by id in Django Serializer not working properly
I am trying to get the last recorded ID in ActiveSession class. I have tested the below view and it is showing the normal results in normal page but when I try to implement the same to my API i keep getting 'ActiveSession' object is not iterable Here is the model: class ActiveSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) log = models.ManyToManyField(Log, related_name='savedlogs') Here is the serializers.py class ActiveSessionSerializer(serializers.ModelSerializer): class Meta: model= ActiveSession fields = '__all__' Here is the api.views @api_view(['GET']) @permission_classes([AllowAny]) def getActiveSession(request, **kwargs): user = get_object_or_404(User, username=request.user) print(user) last_active_session = ActiveSession.objects.filter(user=user).latest('id') serializer = ActiveSessionSerializer(last_active_session, many=True) print(serializer) return Response(serializer.data) here is the traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\User\Desktop\Project\api\views.py", line 67, in getActiveSession return Response(serializer.data) … -
Django IntegrityError: NOT NULL constraint failed with NULLABLE field
When trying to create a superuser in Django, I'm getting the error: django.db.utils.IntegrityError: NOT NULL constraint failed: b3ack_investoruser.watchlist I have a custom user and, the only custom field IS NULLABLE: class InvestorUser(AbstractUser): id = models.AutoField(primary_key=True) watchlist = models.JSONField(default=None, blank=True, null=True) manage.py has: AUTH_USER_MODEL = 'b3ack.InvestorUser' admin.py has: from django.contrib import admin from .models import InvestorUser # Register your models here. admin.site.register(InvestorUser) I have tried python3 manage.py sqlflush I have redone all my migrations. I have deleted previous migrations. None of that works. -
What side effects will come from overriding a custom model manager's create() method?
I am implementing custom model managers, and it looks like the rest_framework by default calls the create() method of a model manager from within its serializer to create a new object. To avoid creating custom views when using a custom model manager, it seems like I could just override the create() method of my custom model manager, and implement standard ViewSets without any customization, but I don't fully understand what side-effects, if any, this will cause. Do I have to call super().create() within the overridden function to get other pieces of django to behave properly? I cannot find anywhere in the django documentation about overriding a custom model manager's create() method, which leads me to think they did not consider it as a use case, and there may be unintended consequences. Is this the case? Why does the standard recommendation seem to be to create a new create_xxx method inside the custom model manager? (i.e. creating a custom user model manager) -
Django manage.py migrate errors
I've been working on a project for CS50-Web for a while now and I was changing some of my models trying to add a unique attribute to some things. Long story short it wasn't working how I wanted so I went back to how I had it previously and now something is wrong and I can get it to migrate the changes to the model. I don't understand what to do because it was working fine before. Please can someone help I so frustrated and annoyed that I've broken it after so many hours of work. Sorry I know this error code is long but I don't know which part is important. Error code `Operations to perform: Apply all migrations: admin, auth, contenttypes, network, sessions Running migrations: Applying network.0019_alter_follower_user...Traceback (most recent call last): File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: new__network_follower.user_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 21, in main() File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
"DateTimeField %s received a naive datetime (%s)
'2022-11-11' this is the input value getting from the front end, RuntimeWarning: DateTimeField PaymentChart.date received a naive datetime (2022-11-18 00:00:00) while time zone support is active. this is the error that coming paydate = datetime.datetime.strptime(date,'%Y-%m-%d').isoformat() this is how i tried to convert the date, and not working, i got this error before, and i added 'tz=datetime.timezone.utc' , it was workin fine then offer.expiry=datetime.datetime.now(tz=datetime.timezone.utc)+datetime.timedelta(days=28) but how can i add tz in strptime ??