Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.1: takes 1 positional argument but 4 were given
Note: I have python version 3.9 on my laptop and I know Django 2.1 is only compatible with python's version 3.7. is python's 3.7 version will solve the issue that I am facing right now? I have 2 year old django 2.1 project and when I type: python manage.py runserver it throws an error of _XMLParser.__init__(self, html, target, encoding) TypeError: __init__() takes 1 positional argument but 4 were given my requirements.txt file packages: amqp==2.5.0 asn1crypto==0.24.0 billiard==3.6.0.0 boto3==1.9.223 botocore==1.12.223 cairocffi==0.9.0 CairoSVG==2.4.2 captcha==0.3 celery==4.3.0 certifi==2018.11.29 cffi==1.15.0 chardet==3.0.4 coreapi==2.3.3 coreschema==0.0.4 cryptography==36.0.2 cssselect2==0.2.2 defusedxml==0.5.0 diff-match-patch==20181111 Django==2.1.5 django-admin-honeypot==1.1.0 django-admin-numeric-filter==0.1.2 django-admin-rangefilter==0.3.10 django-admin-shortcuts==2.0.0 django-admin-toolbox==1.0.0.dev15 django-admin-tools==0.8.1 django-advanced-filters==1.4.0 django-ajax-selects==1.7.1 django-allauth==0.39.1 django-bower==5.2.0 django-braces==1.13.0 django-captcha-admin==0.2 django-celery-beat==1.5.0 django-chart-tools==1.0 django-ckeditor==5.6.1 django-cors-headers==2.0.2 django-extensions==2.1.4 django-filter==2.1.0 django-froala-editor==2.9.2 django-import-export==2.8.0 django-jet==1.0.8 django-js-asset==1.1.0 django-jsonfield==1.0.1 django-material==1.4.1 django-modeladmin-reorder==0.3.1 django-nvd3==0.9.7 django-oauth-toolkit==1.2.0 django-qsstats-magic==1.0.0 django-recaptcha==1.3.0 django-rest-auth==0.9.5 django-rest-framework-social-oauth2==1.1.0 django-rest-swagger==2.2.0 django-storages==1.7.1 django-suit-redactor==0.0.4 django-timezone-field==3.0 django-tinymce==2.8.0 django-wordpress-api==0.2.0 djangorestframework==3.9.0 djangorestframework-jwt==1.8.0 djcacheutils==3.0.0 docutils==0.15.2 drf-yasg==1.12.1 drfdocs==0.0.11 enum34==1.1.6 et-xmlfile==1.0.1 gunicorn==19.9.0 html5lib==1.0.1 idna==2.8 inflection==0.3.1 ipaddress==1.0.22 iso8601==0.1.12 itypes==1.1.0 jdcal==1.4 jet-django==0.4.4 Jinja2==2.10 jmespath==0.9.4 kombu==4.6.3 logger==1.4 Markdown==3.1.1 MarkupSafe==1.1.0 numpy==1.22.3 oauth2-provider==0.0 oauthlib==3.0.0 odfpy==1.4.0 openapi-codec==1.3.2 openpyxl==2.5.12 pandas==1.4.2 Pillow==9.1.0 psycopg2-binary==2.9.3 pycparser==2.19 pyfcm==1.4.5 PyJWT==1.7.1 PyMySQL==0.9.3 pyOpenSSL==18.0.0 Pyphen==0.9.5 PySocks==1.6.8 python-crontab==2.3.8 python-dateutil==2.8.0 python-http-client==3.1.0 python-memcached==1.59 python-nvd3==0.14.2 python-openid==2.2.5 python-slugify==1.1.4 python3-openid==3.1.0 pytz==2018.7 PyYAML==3.13 raven==6.10.0 reportlab==3.6.9 requests==2.21.0 requests-oauthlib==1.2.0 requests-toolbelt==0.9.1 ruamel.yaml==0.15.83 s3transfer==0.2.1 sendgrid==5.6.0 sentry-sdk==0.12.2 simplejson==3.16.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.0.0 stripe==2.22.0 tablib==0.12.1 tinycss2==1.0.2 toml==0.9.6 twilio==6.21.0 unicodecsv==0.14.1 Unidecode==1.0.23 uritemplate==3.0.0 urllib3==1.24.1 … -
want to check my logout function in django is working or not
i have 2 api 1--login 2-- logout i have to make a "SAMPLE_API" which which will be be accessed by only loggedin user can able to access if loggedout user/new user is tring to access that "SAMPLE_API"--- than it should return "UNAUTHORISED" -
Return total value from Subquery - Dja
I have a django query that returns values but I also need to calculate the total quantity in a subquery. When I have only one value in the subquery table it works fine although if more than one i get an error "More than one row returned by a subquery used as an expression". Any help would be appreciated. here is sample of code def get_machine_components(self): return PlantMachineryComponents.objects.filter(machine=self.get_object()).annotate(stock_qty=Sum(Subquery(Stock_DET.objects.filter(stock_hdr__commodity=1275).values('qty')))) -
Annotate Total Created, Modified, and Deleted for each week
Given a Model Item how would I find the total number of items created, modified, and deleted every week? And can this be done in a single database query? from django.db import models class Item(models.Model): created_at = models.DateTimeField(null=True, blank=True) modified_at = models.DateTimeField(null=True, blank=True) deleted_at = models.DateTimeField(null=True, blank=True) My current query returns the same counts for total_created, total_modified, and total_deleted. from django.db.models.functions import TruncWeek Item.objects.annotate( created_at_week=TruncWeek("created_at"), modified_at_week=TruncWeek("modified_at"), deleted_at_week=TruncWeek("deleted_at"), ).values("created_at_week", "modified_at_week", "deleted_at_week").annotate( total_created=models.Count("id"), total_modified=models.Count("id"), total_deleted=models.Count("id"), ) I know it's possible to add filter parameter to Count but I do not know if I can use that here. -
Two HTML Forms in one DJango views
I have two simple HTML forms on one page. I want to create Django view to submit multiple Django forms. I can submit form1 but I have no clue how to submit form2. There is lot of material on internet but they are all about Djanog forms. Please help me with HTML form submission. HTML Form <form action="" method=post name="form1" id="form1"> <input type="text" id="input_form1" name="input_form1"> <button type="submit">Submit</button> </form> <form action="" method=post name="form2" id="form2"> <input type="text" id="form2" name="form2"> <button type="submit">Submit</button> </form> Views.py def index(request): if request.method == 'POST': input_form1 = request.POST.get('input_form1') return render(request, 'index.html', params) Please elaborate how to integrate form2 in Views.py -
cannot update into database using this formset
def updateID(request): EmployeeFormSet = modelformset_factory(Employee, form=EmployeeForm,extra=0) queryset = Employee.objects.filter(EmpID=None) if request.method == "POST": Empform = EmployeeFormSet(request.POST, request.FILES, queryset=queryset) Empform=EmployeeFormSet() if Empform.is_valid(): Empform.save() # Do something. else: Empform=EmployeeFormSet(queryset=queryset) return render(request,'updatingid.html',locals()) I was trying to update the id of a existing employee through formset but it isn't updating -
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '00:00:00'
I have a Django app, where I use raw SQL query to get some item with date before some date. In view.py file I have to query the CourseInfo table to get the courses before a specific date. View.py: query_results = CourseInfo.objects.raw('SELECT * FROM TABLE_course WHERE first_semester <= %s' % (datetime(2021, 1, 1))) But I got this error: 1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '00:00:00' at line 1 How could I fix this error? -
How to pass list of urls from view to tempalte and use them in url reverse
How can I pass a list of URLs to template that corresponds to a specific view? I would like that url {{view}} reverses to theme:view1 views.py def preview(self): context = { "views": ["view1", "view2"] } urls.py app_name="theme" urlpatterns = [ path('view1', view.some_view1, name="view1"), path("view2" view.some_view2, name="view2") ] index.html {% for views in view %} <a href="{{ url {{view}} }}" {% endfor %} Putting {{view}} in quotes makes it a string instead of url -
FileNotFoundError: [Errno 2] using Pipenv
I'm trying to install dependencies in django using pipenv install. Then it responded error message like this in Ubuntu. Does file path in wrong or installation incomplete? Python version - 3.10.4, pip version - pip 22.0.4 from /usr/local/lib/python3.10/dist-packages/pip (python 3.10) /home/username/.local/lib/python3.10/site-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 1.1build1 is an invalid version and will not be supported in a future release warnings.warn( /home/username/.local/lib/python3.10/site-packages/pkg_resources/__init__.py:123: PkgResourcesDeprecationWarning: 0.1.43ubuntu1 is an invalid version and will not be supported in a future release warnings.warn( Creating a virtualenv for this project... Pipfile: /home/username/Documents/codes/storefront2/Pipfile Using /usr/bin/python3 (3.10.4) to create virtualenv... ⠏ Creating virtual environment...created virtual environment CPython3.10.4.final.0-64 in 184ms creator CPython3Posix(dest=/home/username/.local/share/virtualenvs/storefront2-Kl67gUFU, clear=False, no_vcs_ignore=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/username/.local/share/virtualenv) added seed packages: pip==22.0.4, setuptools==62.1.0, wheel==0.37.1 activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator ✔ Successfully created virtual environment! Traceback (most recent call last): File "/usr/local/bin/pipenv", line 8, in <module> sys.exit(cli()) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/pipenv/cli/options.py", line 56, in main return super().main(*args, **kwargs, windows_expand_args=False) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/pipenv/vendor/click/decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) File … -
__init__() missing 1 required keyword-only argument: 'creator'
I am getting type error while setting current user to created_by field in my model forms.py class MyModelForm(forms.ModelForm): class Meta: model = Model fields = ('name',) def __init__(self, *args, creator, **kwargs): super().__init__(*args, **kwargs) self.creator = creator def save(self, *args, **kwargs): self.instance.created_by = self.creator return super().save(*args, **kwargs) views.py class CreatEEView(LoginRequiredMixin, CreateView,): form_class = '' template_name = '' success_url = '' Models.py class MYmodel(models.Model): name = models.CharField() created_by = models.ForeignKey() -
Bootstrap datatable queryParams & pagination
I'm using bootstrap datatable to render my tables. It's almost working like I expected it to work but not quite and I don't know why. <table class="datatable-font-size" data-toggle="table" data-search="true" data-search-align="left" data-pagination="true" data-query-params="queryParams" data-pagination-parts="[pageList]" data-classes="table table-borderless table-striped"> <thead> <tr> <th>Name</th> <th class="ColHideMobile text-center">Intern name</th> <th class="text-end">Last modification</th> </tr> </thead> <tbody> {% for champ in champs %} <tr class="trLink" data-identifiant="{{field.identifiant}}"> <td>{{field.name}}</td> <td class="ColHideMobile text-center">{{field.intern_name}}</td> <td class="text-end">{{field.modif_date|date:"d/m/Y à H:i"}}</td> </tr> {% endfor %} </tbody> </table> I call my function in js, parameter = 15: queryParams("limit") function queryParams(params) { console.log("{{parameter}}") // params.limit = parseInt("{{parameter}}") params = {"limit":parseInt("{{parameter}}"),"offset":0,"order":"asc"} // console.log(params) // console.log(params["limit"]) console.log(JSON.stringify(params)); return params } It goes inside the function queryParams but my datatable never render the number of row limit I want. I don't understand why. I also have a little problem with my pagination: The pagination goes outside the card and my tags are correctly closed so I don't get why it goes sideway. Thank for your help. -
AttributeError: 'str' object has no attribute '_meta' upon migrating
I moved my Inventory model to its own app and reset all migrations. python manage.py makemigrations has no issues, but I get an error upon migrating. Hope someone could point me to a direction since the traceback doesn't seem very helpful to me for resolving the issue. traceback Operations to perform: Apply all migrations: admin, auth, contenttypes, inventory, item, project_site, requisition, sessions, transfer, users Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK ... Applying item.0001_initial... OK Applying project_site.0001_initial...Traceback (most recent call last): File "C:\Users\Bernard\pelicans\imrs-capstone\imrs\manage.py", line 22, in <module> main() File "C:\Users\Bernard\pelicans\imrs-capstone\imrs\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Bernard\pelicans\imrs-capstone\env\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() ... File "C:\Users\Bernard\pelicans\imrs-capstone\env\lib\site-packages\django\db\migrations\operations\models.py", line 92, in database_forwards schema_editor.create_model(model) File "C:\Users\Bernard\pelicans\imrs-capstone\env\lib\site-packages\django\db\backends\base\schema.py", line 364, in create_model if field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' project_site/0001_initial.py from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('item', '0001_initial'), ] operations = [ migrations.CreateModel( name='Cart', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cartItemCount', models.PositiveIntegerField(default=0)), ], ), migrations.CreateModel( name='Site', fields=[ ... ('inventory_items', models.ManyToManyField(blank=True, related_name='inventory_items', through='inventory.Inventory', to='item.Item')), ('siteCart', models.ManyToManyField(blank=True, related_name='siteCart', through='project_site.Cart', to='item.Item')), ], ), ] -
How to implement JWT access mechanism for a Django application (not django rest_framework)
I'm actually looking for a way to implement. I have a django project folder (only django, not django rest framework). All the views across all the apps in the project will be returning a JsonResponse parsed response. (Instead of rendering to a template) A basic view looks like this, with necessary imports from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.http import JsonResponse @csrf_exempt @require_http_methods(['POST']) def sample_route(request): # validate request object, use them to query / process data # .. some more statements result = {"a": 1, "b": 2} return JsonResponse(result, status=200) I understand that this isn't a conventional practice like in a DRF project, but I would like to make such routes accessible by tokens (supposedly JWT). Can I get suggestions about how this would be possible - like with or without depending on djangorestframework library or any extensions or any other JWT associated libraries. Thanks -
Join with OneToOneField relathionship django
I have two models with OneToOneField relationship and I want to somehow join them and be able to access the attribute of the one model from the other. My models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) HVAC_flex = ArrayField(models.FloatField(blank=True, null=True)) DHW_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) My views.py is as follows: @api_view(['GET']) def result(request): results_list = Result.objects.all() num_results_list = Result.objects.all().count() if num_results_list < RES_LIMIT: serializer = ResultSerializer(results_list, many=True) query = serializer.data return Response(query) else: results_list = Result.objects.order_by('-created_at')[:RES_LIMIT] serializer = ResultSerializer(results_list, many=True) query = serializer.data return Response(query) Right now the query is as follows: [OrderedDict([('id', 1), ('HVAC_flex', [49.0, 27.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), ('DHW_flex', [4.0, 0.0, 45.0, 4.0, 20.0, 33.0, 42.0, 13.0]), ('lights_flex', [6.0, 8.0, 0.0, 0.0, 0.0, 18.0, 28.0, 0.0]), ('event_id_result', None)]), OrderedDict([('id', 2), ('HVAC_flex', [0.0, 0.0, 15.0, 0.0, 23.0, 6.0, 0.0, 0.0]), ('DHW_flex', [1.0, 2.0, 7.0, 47.0, 1.0, 19.0, 37.0, 9.0]), ('lights_flex', [40.0, 28.0, 34.0, 6.0, 8.0, 43.0, 6.0, 0.0]), ('event_id_result', None)]), OrderedDict([('id', … -
Django admin - admin inheritance
When registering django admin, I inherited another admin, but I don't know why the model of list_display is changed. Let me explain the situation in detail with code. @admin.register(User) class UserAdmin(models.Model): list_display = [a.name for a in User._meta.concrete_fields] @admin.register(Sales) class SalesAdmin(UserAdmin): pass According to the code above, SalesAdmin Admin appears to inherit from UserAdmin. In this case, shouldn't list_display of User model appear in list_display? I don't understand why the list_display of Sales Model comes out. If I want to display the list_display of the Sales model while inheriting UserAdmin, shouldn't I have to redeclare the list_display as shown below? @admin.register(User) class UserAdmin(models.Model): list_display = [a.name for a in User._meta.concrete_fields] @admin.register(Sales) class SalesAdmin(UserAdmin): list_display = [a.name for a in Sales._meta.concrete_fields] I did not redeclare list_display, but I do not understand whether it is automatically output as the list_display of the changed model. If anyone knows, please explain. -
How to get POST and create message on Django using DetailView
I have Post model and Message model. I want to get POST, create message on one post and preview it. I have ValueError Cannot assign "<bound method PostDetailView.post of <blog.views.PostDetailView object at 0x7fa9a370b8>>": "Message.post" must be a "Post" instance. at body = request.POST.get('body') How can I do this? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) body = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] views.py class PostDetailView(DetailView): model = Post def post(self, request, *args, **kwargs): message = Message( user = request.user, post = self.post, body = request.POST.get('body') ) message.save() return super(PostDetailView,self).post(request, *args, **kwargs) -
UnboundLocalError local variable 'context' referenced before assignment Django
I get the error below immediately after i add a new root url inside the root urls.py. When i remove the dashboard view, url and i try to load index view, it renders successfully. What am i doing wrong or what can i do to resolve the issue. Error message UnboundLocalError at /blogapp/ local variable 'context' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/blogapp/ Django Version: 4.0.2 Exception Type: UnboundLocalError Exception Value: local variable 'context' referenced before assignment My views from multiprocessing import context import re from django.shortcuts import render from django.http import HttpResponse from .odd_finder_func import * def index(request): if request.method == 'POST': odd1 = float(request.POST.get('odd1')) odd2 = float(request.POST.get('odd2')) odd3 = float(request.POST.get('odd3')) func_def = odd_finder_true(odd1, odd2, odd3) context = { 'Juice': func_def['Juice'], 'TotalImpliedProbability': func_def['TotalImpliedProbability'], 'HomeOdd': func_def['HomeOdd'], 'DrawOdd': func_def['DrawOdd'], 'AwayOdd': func_def['AwayOdd'], 'Home_True_Odd': func_def['Home_True_Odd'], 'Draw_True_Odd': func_def['Draw_True_Odd'], 'Away_True_Odd': func_def['Away_True_Odd'], 'True_Probability': func_def['True_Probability'] } context = context return render(request, 'index.html', context) def dashboard(request): return render(request, 'dashboard.html') blogapp urls.py from django.urls import path from .views import * from . import views urlpatterns = [ path('', views.index, name='index'), ] myblog urls.py the root file. from django.contrib import admin from django.urls import path, include from blogapp import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.dashboard, name='dashboard'), … -
Querying within a list of dicts within a Django model JSONField
I'm trying to query an element within a list of dicts in a Django JSONField. I can find similar questions to mine but not one that covers what I'm trying to do. It seems like it should be simple and fairly common so I suspect I'm missing something simple. So. to expand slightly on the example in the Django docs Let's say I have a Dog model with a JSONField named data and it has some data like so: Dog.objects.create(name='Rufus', data = {"other_pets": [{"name", "Fishy"}, {"name": "Rover"}, {"name": "Dave"}]} ) There's a key named "other_pets" which is a list of dicts. I would like to write a query which returns any models which includes a dict with the key name=="Dave" I am able to directly do this if I refer to the element by the index, eg: Dog.objects.filter(data__other_pets__2="Dave") Would return me the row, but I need to reference the index of the list element, and both the position of the item I'm looking up, and the size of the list vary among models. I thought that maybe: Dog.objects.filter(data__other_pets__contains={"name":"Dave"}) Would work but this returns no elements. Is what I'm trying to do possible? As an aside, is it possible to add … -
Django project requirements missing after Ubuntu Jellyfish update
After updating Ubuntu to the latest update, Pycharm tells me required packages are missing but the virtual environment is activated and the packages are all there. Trying to runserver results in ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Trying to install packages again results in Invalid Python SDK Anyone having this problem after the update? Thanks in advance. -
Django - Protect/Redirect a page after session required to see that page is deleted
I use an external API for authentification. In the view i put a request.session to display, after correct login, user information that im getting from that API.Everything work (log in/ log out/ info displays). I the template i show user info only if is a session active/valid after correct login. But after logout (delete that session in the view logout) if i try to access that info page the info is not show but get an error "KeyError at..." | and name of the session. Is good that now show info but i want to redirect from that page if is not a session active/valid and i don't know how. I tried to use @login_required but in my case i don't user is not ok because i use authentification with an API. Any suggestion how to redirect from the template/page (view def dashboard) if the session is not prezent/was deleted ? Thank you. Below my settings view.py def loginPL(request): if request.method == 'POST': client = Client(wsdl='http://.....Http?wsdl') marca = request.POST['marca'] parola = request.POST['parola'] try: login = (client.service.Login(marca, parola)) except: messages.error(request, "") if login > 0: # print(login) request.session['loginOk'] = login return redirect('login:dashboard') else: messages.error(request, "utilizatorul sau parola nu sunt corecte / … -
Django Dependent/Chained Dropdown List in a filter
I am using Django to implement my web page; in this page I have a classic item list that I manage with a for loop. I also implement a filter as a form (with search button) to filter the items. I know how can I implement a dropdown List (first code) and I know how can I implement a form filter (second code). DROPDOWN LIST (JQUERY CODE) <script> $( document ).ready(function() { var $provvar = $("#provddl"); $uffvar = $("#uffddl"); $options = $uffvar.find('option'); $provvar.on('change',function() { $uffvar.html($options.filter('[value="'+this.value+'"]')); }).trigger('change'); }); </script> FORM FILTER <form> <div> <label>C: </label> {{ myFilter.form.C }} </div> <div> <label>D: </label> {{ myFilter.form.D }} </div> <button type="submit">Search</button> </form> My problema is that I don't know how can I implement a the Dependent Dropdown List in my filter. -
I need a detailed explanation of the DJANGO get_context_data() function below
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context Please i need a detailed explanation of the function above especially on line: context['now'] = timezone.now() -
Django make search side widget conncet html
Sorry my english not good please forgive me Hi I want make post search side widget i make search widget is can work but i can't connect html side search widget and work how can i connet it enter image description here my search widget of html <div class="card mb-4"> <div class="card-header">Search</div> <div class="card-body"> <div class="input-group"> <input class="form-control" id="search-input" type="text" placeholder="Enter search term..." aria-label="Enter search term..." aria-describedby="button-search"/> <button class="btn btn-primary" id="button-search" type="button" onclick="searchPost();">Go!</button> </div> </div> </div> and i want connet html search widget about this! <h1>Blog Search</h1> {% if search_info %}<small class="text-muted">{{ search_info }}</small>{% endif %} <br> <form action="." method="post"> {% csrf_token %} {{ form.as_table }} <input type="submit" value="Submit" class="btn btn-primary btn-sm"> </form> <br/><br/> {% if object_list %} {% for post in object_list %} <h2><a href='{{ post.get_absolute_url }}'>{{ post.title }}</a></h2> {{ post.modify_date|date:"N d, Y" }} <p>{{ post.description }}</p> {% endfor %} {% elif search_term %} <b><i>Search Word({{ search_term }}) Not Found</i></b> {% endif %} -
KeyError: 'created_at' in django rest serializer
I am getting the following error, while I am trying to save some data coming from a POST request to a database: KeyError: 'created_at' My views.py is as follows: @api_view(['GET', 'POST']) def event(request): if request.method == 'POST': serializer = EventSerializer(data=request.data) if serializer.is_valid(): DR_notice = serializer.data['dr_notice_period'] DR_duration = serializer.data['dr_duration'] DR_trigger = serializer.data['created_at'] DR_start, DR_finish, timesteps = DR_event_timesteps(DR_notice, DR_duration, DR_trigger) serializer.save(user_id_event=request.user, dr_start=DR_start, dr_finish=DR_finish, timesteps=timesteps) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) My models.py is as follows: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) dr_start = models.DateTimeField(blank=True, null=True) dr_finish = models.DateTimeField(blank=True, null=True) timesteps = models.IntegerField(blank=True, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) class Result(models.Model): event_id_result = models.OneToOneField(Event, on_delete=models.CASCADE, null=True) HVAC_flex = ArrayField(models.FloatField(blank=True, null=True)) DHW_flex = ArrayField(models.FloatField(blank=True, null=True)) lights_flex = ArrayField(models.FloatField(blank=True, null=True)) My serializers.py is as follows: from rest_framework import serializers from vpp_optimization.models import Event, Result class EventSerializer(serializers.ModelSerializer): created_at = serializers.DateTimeField(format="%d-%m-%Y %H:%M:%S", read_only=True) class Meta: model = Event fields = ('__all__') class ResultSerializer(serializers.ModelSerializer): HVAC_flex = serializers.ListField(child=serializers.FloatField()) DHW_flex = serializers.ListField(child=serializers.FloatField()) lights_flex = serializers.ListField(child=serializers.FloatField()) class Meta: model = Result fields = ('__all__') As I can understand created_at takes its value when … -
Rich text editor for Django with comments/annotation (open source)
Is there anyone succeeded integrating any rich text editor through Django along with inline comments option? I refer inline comment as highlighting a word or sentence in the text editor and adding comments (annotation). When and who commented to be displayed on the side like a thread. I have tried ckeditor, tinymce, summernote etc and nothing seems to have this functionality without premium licensing. Any leads?