Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to create a report of all update history of my lead model in django
I have a Training_Lead model, in my team i have 5-6 members who can edit this lead from there id's. I want to create a report of Update history that who is update lead and when, fro that i have create a two coloum names last_modification and last_modification_time which is automaticaly update when someone update lead. class Training_Lead(models.Model): handel_by = models.ForeignKey(UserInstance, on_delete=models.PROTECT) learning_partner = models.ForeignKey( Learning_Partner, on_delete=models.PROTECT, blank=False, null=False) assign_to_trainer = models.ForeignKey( Trainer, on_delete=models.PROTECT, null=True, blank=True) course_name = models.CharField(max_length=2000) lead_type = models.CharField(max_length=2000) time_zone = models.CharField(choices=(('IST', 'IST'), ('GMT', 'GMT'), ('BST', 'BST'), ( 'CET', 'CET'), ('SAST', 'SAST'), ('EST', 'EST'), ('PST', 'PST'), ('MST', 'MST'), ('UTC', 'UTC')), max_length=40, blank=False, null=False) getting_lead_date = models.DateTimeField(null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) lead_status = models.CharField(choices=(('Initial', 'Initial'), ('In Progress', 'In Progress'), ('Follow Up', 'Follow Up'), ( 'Cancelled', 'Cancelled'), ('Confirmed', 'Confirmed'), ('PO Received', 'PO Received')), max_length=40, blank=False, null=False) lead_description = models.CharField(max_length=9000, blank=True, null=True) last_modification = models.CharField(null=False, blank=False, max_length=500) last_modification_time = models.DateTimeField(auto_now_add='True') def __str__(self): return str(self.assign_to_trainer) class Meta: ordering = ['start_date'] -
Django UserPassesTestMixin causes duplicate sql query
So, in my Django project, I have a Class-Based View that uses UserPassesTestMixin. Within it, I use test_func to check whether the object belongs to the user (or admin). But I see duplicate SQL queries happen. I suspect test_func which has self.get_object causes that. Pls, advise how to avoid that duplicating. Here is my view: class PostUpdateView(UserPassesTestMixin, UpdateView): permission_denied_message = "Access for staff or profile owner!" def test_func(self): return ( self.request.user.is_staff or self.request.user.pk == self.get_object().author_id ) model = Post queryset = Post.objects.all().select_related("author") form_class = UpdatePostForm template_name = "diary/post-update.html" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Raise KeyError(key)
Key error is raised but config.ini file has the same key and I can read that using configparser. But while executing it throws the key error. What can be the solution? Tried commenting out the those keys. But it throws a different error. -
Issue with Django CSRF and Basic Authentication
I am having a lot of trouble authenticating Basic Auth Http requests in Django from my Heroku web server. I have tried a lot of different solutions to fix this issue. First I was seeing Forbidden (Referer checking failed - no Referer.) so I had to add extra Origin and Referer headers to the incoming requests. Now I am stuck on Forbidden (CSRF cookie not set.). No matter what I try, I cannot seem to get ride of the error. The odd thing is that this works when I try to test this locally and hit the endpoint from a curl originating from my local machine, yet it fails from the external site (which I have less control over). This curl works: curl -X POST -u 'USERNAME:PASSWORD' -d '["test"]' https://test.mysite.com/api I have taken bits from this solution: https://stackoverflow.com/a/30875830/2698266 My relevant code looks like the following: in settings.py MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", ... ] ... REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication", ), "EXCEPTION_HANDLER": "rollbar.contrib.django_rest_framework.post_exception_handler", } ... ALLOWED_HOSTS = ["*.mysite.com", "mysite.herokuapp.com", "127.0.0.1", "external.com"] ... CORS_ORIGIN_WHITELIST = ["https://external.com"] CSRF_TRUSTED_ORIGINS = ["https://external.com"] CORS_REPLACE_HTTPS_REFERER = True My API endpoint (a webhook): from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view, authentication_classes, renderer_classes from rest_framework.authentication … -
How to pass and return a queue to and from a celery task in Django?
I'm trying to pass and return the queue q to and from the task test() in Django as shown below: # "views.py" import queue from .tasks import test from django.http import HttpResponse def call_test(request): q = queue.Queue() q.put(0) test.delay(q) # Here return HttpResponse("Call_test") # "tasks.py" from celery import shared_task @shared_task def test(q): q.queue[0] += 1 return q # Here But, I got the error below: Object of type Queue is not JSON serializable So, I used __dict__ with the queue q as shown below: # "views.py" import queue from .tasks import test from django.http import HttpResponse def call_test(request): q = queue.Queue() q.put(0) test.delay(q.__dict__) # Here return HttpResponse("Call_test") # "tasks.py" from celery import shared_task @shared_task def test(q): q.queue[0] += 1 return q.__dict__ # Here But, I got the error below: Object of type deque is not JSON serializable So, how can I pass and return the queue q to and from the task test()? -
Django search bar isn't giving correct results
views.py from django.shortcuts import render from ecommerceapp.models import Product from django.db.models import Q def searchResult(request): products=None query=None if 'q' in request.GET: query = request.GET.get('q') products=Product.objects.all().filter(Q(name__contains=query) | Q(desc__contains=query)) return render(request,'search.html',{'query':query,'products':products}) In views.py I have imported a model named 'Product' of another application. search.html {% extends 'base.html' %} {% load static %} {% block metadescription %} Welcome to FASHION STORE-Your Beauty {% endblock %} {% block title %} Search-FASHION STORE {% endblock %} {% block content %} <div> <p class="text-center my_search_text">You have searched for :<b>"{{query}}"</b></p> </div> <div class="container"> <div class="row mx_auto"> {% for product in products %} <div class="my_bottom_margin col-9 col-sm-12 col-md-6 col-lg-4" > <div class="card text-center" style="min-width:18rem;"> <a href="{{product.get_url1}}"><img class="card-img-top my_image" src="{{product.image.url}}" alt="{{product.name}}" style="height:400px; width:100%;"></a> <div class="card_body"> <h4>{{product.name}}</h4> <p>₹{{product.price}}</p> </div> </div> </div> {% empty %} <div class="row mx_auto"> <p class="text-center my_search_text">0 results found.</p> </div> {% endfor %} </div> </div> {% endblock %} navbar.html <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item dropdown {% if 'ecommerceapp' in request.path %} active {% endif %} "> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Shop </a> <ul class="dropdown-menu"> … -
Django 'NoneType' object has no attribute 'socialaccount_set'
models.py class Post(models.Model): title = models.CharField(max_length=30) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) def get_avatar_url(self): if self.author.socialaccount_set.exists(): return self.author.socialaccount_set.first().get_avatar_url() else: return 'https://dummyimage.com/50x50/ced4da/6c757d.jpg' part of landing.html <div class="col"> <h2>Recent Posts</h2> {% for post in recent_posts %} <div class="card"> <div class="card-body"> <h6> <a href="{{post.get_absolute_url}}" class="text-decoration-none text-dark"> {{post.title}} </a> </h6> <span class="badge"> <img class="rounded-circle" width="20px" src="{{post.get_avatar_url}}"> {{post.author.username}} {{post.created_at}} </span> </div> </div> {% endfor %} </div> Error message 'NoneType' object has no attribute 'socialaccount_set' Error during template rendering In template /.../landing.html, error at line 34(which includes '{{post.get_avatar_url}}' source url.) It works okay when I logged in but it shows the error when it's not logged in instead of showing the dummyimage. What am I missing? Html and Post model are in the different apps. views.py for the secondApp app! from firstApp.models import Post def landing(request): recent_posts = Post.objects.order_by('-pk')[:3] return render(request, 'secondApp/landing.html', { 'recent_posts': recent_posts, }) -
Access file from user system while running code from live server django
I want to access and execute .bat file from end-user system while my code running on server. Indirectly I want to access local system file of user system. Python / Django solution. -
Django - pass the value for detail to template
There is a view for detail: def get_viewNum(request, numNom): md = Nomenclature.objects.get(pk=numNom) all_changes_for_md = Changes.objects.filter(numNomenclature_id=md.numNom) return render(request,'Sklad/viewNum.html',context = {'nomenclature':md, 'changes':all_changes_for_md}) There is also a view to display the table: class TableView(ListView): model = Nomenclature context_object_name = 'nm' template_name = 'Sklad/viewTable.html' In template, I output a table and I want that when the button is clicked, there is a transition to the detail of the desired nomenclature. My template: /// {% for item in nm %} <tr> <td>{{item.numNom}}</td> <td>{{item.nameNom}}</td> <td>{{item.quantity}}</td> <td>{{item.numPolk}}</td> <td><a href="{% url 'prosmotr' %}">Просмотр</a></td> <td><button>Печать</button></td> </tr> {% endfor %} /// How do I pass the desired numNom to the url detail string? If you use this: ... <td><a href="{% url 'prosmotr' item.numNom %}">Просмотр</a></td> ... Returns an error: NoReverseMatch at /table/ Reverse for 'prosmotr' with arguments '('',)' not found. 1 pattern(s) tried: ['news/(?P[^/]+)/\Z'] My urls.py: urlpatterns = [ path('', home, name='rashod'), path('add_changes/',CreateChanges.as_view(), name = 'add_changes'), path('save', save), path('inventriz/', inventriz, name='invent'), path('inventriz/inventr', inventr, name='add_invent'), path('news/<str:numNom>/',get_viewNum, name='prosmotr'), path('table/', TableView.as_view(), name = 'viewTable') ] -
Image cannot be displayed after saving the data in Django. The code for it is given below
Problem Statement: In shown image, default profile pic is visible but i need uploaded photo to be displayed here when i upload and saved in the database.I am using django framework. What have I Tried here? In setting.html file,The below is the HTML code for what is have tried to display image, bio, location. The problem may be at first div image tag. Though the default profile picture is visible but which i have uploaded is not displaying in the page nor able to save in database. <div class="col-span-2"> <label for="">Profile Image</label> <img width = "100" height = "100" src="{{user_profile.profileimg.url}}"/> <input type="file" name='image' value = "" placeholder="No file chosen" class="shadow-none bg-gray-100"> </div> <div class="col-span-2"> <label for="about">Bio</label> <textarea id="about" name="bio" rows="3" class="shadow-none bg-gray-100">{{user_profile.bio}}</textarea> </div> <div class="col-span-2"> <label for=""> Location</label> <input type="text" name = "location" value = "{{user_profile.location}}" placeholder="" class="shadow-none bg-gray-100"> </div> In views.py file,the below function is the views file settings page logic for displaying the image, bio, location. If the image is not uploaded, it will be default profile picture. If image is not none then the uploaded image is displayed. But I am not getting what is the mistake here in my code. @login_required(login_url='signin') def settings(request): user_profile = Profile.objects.get(user … -
how can i do "removeEmptyTag:False" in django-ckeditor in settings.py
source output django-ckeditor automatic remove empty tag :{ source output -
django + angular project. sometimes break my uibmodel
django view prep_data = service.PreparationsData('preparation/get_order_comp_details/',{"order_number": order_num}) response = prep_data.get_data() result = json.loads(response.text) rem = result["remark"].replace("\n",'\\n') context = { "order_number": order_num, "re" : rem } return render(request, "sendion.html",context) uibmodel var showsourcingverificationModal = $uibModal.open({ templateUrl: templateUrl, controller: 'sendtooModalCtrl', scope: $scope, size: 'lg', backdrop: false, resolve: { dataModal: function () { return { ord_num : order_num }; }, }, }); im trying to fill the field with $('#id_dn).text(value) im trying to fill the field with $('#id_dn).text(value) <script type="text/javascript"> $('#id_remarks').text('{{remark}}'); $('#idvalidation').hide(); (function () { sendtoSocinModalInit(); })(); </script> -
keep my data test when running TestCase in django
i have a initail_data command in my project and when i try to creating my test database and run this command "py manage.py initail_data" its not working becuse this command makes data in main database and not test_database, actually cant undrestand which one is test_database. so i give up to use this command,and i have other method to resolve my problem . and i decided to create manual my inital_data. inital_data command actually makes my required data in my other tables. and why i try to create data? becuse i have greater than 500 tests and this tests required to other test datas. so i have this tests: class BankServiceTest(TestCase): def setUp(self): self.bank_model = models.Bank self.country_model = models.Country def test_create_bank_object(self): self.bank_model.objects.create(name='bank') re1 = self.bank_model.objects.get(name='bank') self.assertEqual(re1.name, 'bank') def test_create_country_object(self): self.country_model.objects.create(name='country', code=100) bank = self.bank_model.objects.get(name='bank') re1 = self.country_model.objects.get(code=100) self.assertEqual(re1.name, 'country') i want after running "test create bank object " to have first function datas in second function actually this method Performs the command "initial_data". so what is the method for this problem. i used unit_test.TestCase but it not working for me. this method actually makes test data in main data base and i do not want this method. or maybe i used … -
Connect existing Django server project and to local host
I have a django project that have been maintaining on the cpanel server over 3years now with close to 30k lines of code, now I want to work with it on local machine for maintainance but after downloading codes and migrating new database, there are about thousands of database variable that reply on populated database field and will take me months to figure all out.. Anyway I can make a mini copy of my server mysql database and connect or is there any Starndard way to resolve this issue?? -
I have used djangorest to create an api but when i make a post request it returns an error saying 400 BAD request
this is the serializer : class PostSerializer(serializers.ModelSerializer): def create(self, validated_data): post = Post.objects.create( author=validated_data["author"], title=validated_data["title"], text=validated_data["text"] ) post.save() return post class Meta: model = Post fields = ["author", "title", "text", "pk", 'publicationDate'] this is the api view : class PostList(GenericAPIView, ListModelMixin, CreateModelMixin): queryset = Post.objects.all() serializer_class = PostSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) and this is the request I`m making : axios.post('/api/posts/', form, { "headers": { 'Content-Type': 'application/json', } }) .then(response => console.log(response.data)) this is the error it returns POST http://127.0.0.1:8000/api/posts/ 400 (Bad Request) I have been at this problem for days now and i have tried everything but it just wont work -
How to pass a javascript variable in html to views.py?
I am currently trying to make an website using django. And i faced a problem like i wrote in title. What i want to make is like this, first of all, shop page shows all products. But, when a user select a brand name on dropdown menu, shop page must shows only that brand products. To do this, i have to get a variable which a user select on dropdown menu, and my view function should run at the same time. Please let me know how can i resolve this. i made a dropdown in html as below. <shop_test.html> <form action="{% url 'shop' %}" method="get" id="selected_brand"> <select name="selected_brand" id="selected_brand"> <option value="ALL">Select Brand</option> <option value="A">A_BRAND</option> <option value="B">B_BRAND</option> <option value="C">C_BRAND</option> </select> </form> <script type="text/javascript"> $(document).ready(function(){ $("select[name=selected_brand]").change(function () { $(".forms").submit(); }); }); </script> and my views.py is as below. def ShopView(request): brand_text = request.GET.get('selected_brand') if brand_text == None: product_list = Product.objects.all() elif brand_text != 'ALL': product_list = Product.objects.filter(brand=brand_text) else: product_list = Product.objects.all() context = { 'brand_text': brand_text, 'product_list': product_list, } return render(request, 'shop_test.html', context) i tried to google it a lot of times, but i counldn't resolve this. -
I am facing issue in image uploading through API in django
class ResidenceAreaImage(APIView): def post(self, request): if request.FILES.get("image", None) is not None: img = request.FILES["image"] img_extension = os.path.splitext(img.name)[1] save_path = "/media/company_logo/" # if not os.path.exists(save_path): os.makedirs(os.path.dirname(save_path), exist_ok=True) img_save_path = "%s%s%s" % (save_path, str(uuid.uuid4()), img_extension) with open(img_save_path, "wb+") as f: for chunk in img.chunks(): f.write(chunk) # data = {"success": True} else: raise Exception("plz add image!!!") return Response({"file_url":img_save_path}) -
Why Django can't find static folder in BASE_DIR?
I have these directories: └── MY_FOLDER ├── MY_PROJECT │ └── settings.py │ ├── MY_APP ├── STATIC │ └── style.css ├── MEDIA └── manage.py In the settings.py I've indicated: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATICFILES_DIR = (os.path.join(BASE_DIR,'static')) When I print(STATICFILES_DIR) I get a path: MY_FOLDER/STATIC - what is exactly I wanted. But Django don't see any css there, in that folder. I tried to put my css to MY_APP/STATIC and it started to work correctly. But I want to have it not in MY_APP but in BASE_DIR/STATIC. How to do it? Or if it is impossible, how to make a correct path for STATICFILES_DIR to let it search my statics in all apps I'll add in the future. Not only in one app by doing this: STATICFILES_DIR = (os.path.join(BASE_DIR,'MY_APP','static')) Thanks. -
Auto import suggestion django functions in Vscode
hello everyone I am having a problem the visual studio code autoimport suggestion for django functions does not work for me. I appreciate the help. enter image description here pylance don't search in the django modules -
How can I set and append in column with conditional case in Django?
I want to run this sql query in Django UPDATE `TABLE` SET `COLUMN` = (CASE WHEN `COLUMN` = "" THEN '100' ELSE CONCAT(`COLUMN`,'100') END) WHERE `ID` IN [id1,id2,id3]; I tried this from django.db.models import Case, When, F Table.object.filter(id__in=[id1,id2,id3]). update(column= Case( When(column="",then="100"), default= column + "100", ) ) I dont know how to put concat in default here. Please help. -
django how should I create my multiple user
I have two different users, one requesting for repairs (Office) and the inspector/repairman which is (Technician). I was wondering if this is a good idea to make both officeid/techid in customUser like this or there's a better way this is the values of both office and technician, We have hr/accounting for example then EMP-** this is my full erd so far I might change somethings based on your recommendations -
Django Admin is not allowing me to change any user settings after implementing a AbstractUser
Following a video on Youtube I want to creat a website with different Roles for students and teachers. I also would like to save off the School ID in to the user. Here is what I want to change but when I hit save it does nothing. I've tried creating custom forms to use for the create and change but it doesn't seem to matter. I feel like I missed typed something in the model.py or I'm missing something. Creating users works like a charm so that's why I'm confused why it wouldn't update a user correctly. I have done a fully custom user class before but shouldn't need to for this simple of change. In the setting is have this line AUTH_USER_MODEL = "account_app.User" models.py from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db.models.signals import post_save from django.dispatch import receiver class School(models.Model): name = models.CharField('School Name', max_length=240) address1 = models.CharField('Address 1', max_length=240) address2 = models.CharField('Address 2', max_length=240) city = models.CharField('City', max_length=240) district = models.CharField('District', max_length=240) state = models.CharField('State', max_length=2) zip_code = models.IntegerField('Zip Code') country =models.CharField('Country', max_length=240) phone = models.IntegerField('School Phone Number') time_zone = models.CharField(max_length=50) def __str__(self): return f'{self.name}' class User(AbstractUser): class Role(models.TextChoices): ADMIN = "ADMIN", "Admin" STUDENT … -
Filtering Data from Firestore in Django, passing to HTML template
I have data stored in Firestore and i would like to get data from a collection, filter it and publish it in HTML template. I am using Django as the framework. VIEWS.py from django.shortcuts import render import pyrebase from firebase_admin import firestore import datetime db = firestore.Client() config = { "apiKey": "xxxxxx", "authDomain": "xxxxxx.firebaseapp.com", "databaseURL": "https://xxxxxx.firebaseio.com", "projectId": "xxxxxx", "storageBucket": "xxxxxx.appspot.com", "messagingSenderId": "xxxxxx", "appId": "xxxxxx", "measurementId": "xxxxxx", "serviceAccount": "xxxxxx.json", } # DATABASE firebase = pyrebase.initialize_app(config) authe = firebase.auth() database = firebase.database() print(database) # TIME & DATE today_date = datetime.datetime.now() tomorrow_date = today_date + datetime.timedelta(days=1) games_today = today_date.strftime("%Y-%m-%d") games_tomorrow = tomorrow_date.strftime("%Y-%m-%d") print(games_today) print(games_tomorrow) # NBA EVENT DATA def xxxxx_basketball_nba_events(request): nba_events = db.collection('xxxxx_au').document('basketball_nba').collection('event_info').stream() event_info = [doc.to_dict() for doc in nba_events] nba_games = sorted(event_info, key=lambda k: k['event_start'], reverse=True) print(nba_games) return render(request, 'html/nba.html', {'data': nba_games}) HTML template {% block content %} <table class="table table-striped" style="padding: 15px; width: 1000px"> <thead> <tr> <th scope="col">Event ID</th> <th scope="col">Competition</th> <th scope="col">Event Name</th> <th scope="col">Event Start</th> <th scope="col">Event Status</th> </tr> </thead> {% for xxx_nba in data %} <tbody> <tr> <th>{{xxx_nba.event_id}}</th> <td>{{xxx_nba.competition}}</td> <td>{{xxx_nba.event_name}}</td> <td>{{xxx_nba.event_start}}</td> <td>{{xxx_nba.event_status}}</td> </tr> </tbody> {% endfor %} </table> {% endblock %} HTML Output 1018936256 NBA Los Angeles Lakers - Portland Trail Blazers 2022-12-01T03:30:00Z NOT_STARTED 1018936251 NBA Sacramento Kings … -
Django nested model formsets only save the first form
I have two formsets that I created with modelsetfactory. When I give the extra field manually, it saves all the forms. But when I add a form dynamically, it only saves the first form. Before using nested formset, I did not encounter such an error, but I had to redesign my first form as a formset. As seen in the picture, it saves only the first of the forms that I add dynamically. Saves "Test Product" but not "Test Product 2" here is my models : class UserTask(models.Model): id = models.AutoField(primary_key=True) user_id = models.ForeignKey(User,on_delete= models.CASCADE, verbose_name='User',null=True, related_name="user_id") task_types_id = models.ForeignKey(TaskTypes,on_delete=models.CASCADE,verbose_name="Task Type", default=None) subunit_id = models.ForeignKey(WorksiteSubunit,on_delete= models.CASCADE,verbose_name="Subunit",null=True, default=None) store_house_id = models.ForeignKey(StoreHouse,on_delete= models.CASCADE,verbose_name="Store House",null=True) description = models.TextField(max_length=255) author = models.ForeignKey(User,on_delete= models.CASCADE,null=True, related_name="author_id") class TaskSources(models.Model): id = models.AutoField(primary_key=True) user_task_id = models.ForeignKey(UserTask,on_delete=models.CASCADE) product_id = models.ForeignKey(Product,on_delete=models.CASCADE,verbose_name="Product",null=True) product_amount = models.FloatField(max_length=255,verbose_name="Product Amount",null=True) def __str__(self): return str(self.user_task_id.store_house_id) here is my forms : class UserTaskForm(forms.ModelForm): class Meta: model = UserTask fields = ['user_id','task_types_id','store_house_id','description'] class TaskSourcesForm(forms.ModelForm): class Meta: model = TaskSources fields = ['product_id', 'product_amount'] TaskSourcesFormSet = modelformset_factory( TaskSources, fields=('product_id', 'product_amount',), extra=1, ) UserTaskFormFormSet = modelformset_factory( UserTask, fields=('user_id','task_types_id','store_house_id','description',), extra=1, ) here is my views : @login_required(login_url="login") def addUserTask(request): user_task_form = UserTaskFormFormSet(queryset=UserTask.objects.none(),initial=[{'user_id': request.user}]) formset = TaskSourcesFormSet(queryset=TaskSources.objects.none()) if request.method == 'POST': user_task_form … -
Enter a valid date/time - Django Datetime Picker
I'm creating a CRUD application in Django, and one of the fields in the data requires the user to enter a datetime input. This was working smoothly until this evening when I started to work on it again, however I'm getting the below error when I try to add any data the the model. start_datetimeEnter a valid date/time. [01/Dec/2022 00:34:39] "POST /activities/new/ HTTP/1.1" 200 2253 I've tried quite a few ways to resolve this but nothing seems to be working; below if the code I have to create the activity class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ('name', 'start_datetime', 'end_time', 'location', 'town', 'description') labels = { 'name': 'Activity Type', 'start_datetime': 'Date & Time of Activity', 'end_time': 'End Time', 'location': 'County', 'town': 'Town (optional)', 'description': 'Description', } widgets = { 'start_datetime': DateTimePickerInput(), 'end_time': TimePickerInput(), } class DateTimePickerInput(forms.DateTimeInput): input_type = 'datetime-local' This is the model field for the start_datetime: start_datetime = models.DateTimeField() Does anyone have any ideas on how to resolve this? Thanks!