Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CKEditor Restrict Image Properties
Currently im using CKeditor to allow user to write nice looking posts. Now when i try to integrate the image option, I only want the user to upload images, when i click on the image symbol it shows: ImageInfo (lets the user choose an image from server folder), Link for a web image, Upload to open a file browser and let user choose his own, and Advanced, which i do not know about. I only want the user to be able to upload images from his computer. How do i deactivate the other properties? here is my config in settings.py: CKEDITOR_CONFIGS = { 'default': { 'width': '150%', 'toolbar': 'Custom', # Specify Custom Shit - GPL License - 'toolbar_Custom': [ ['Bold', 'Italic', 'Underline', '-', 'Image', 'Link', 'CodeSnippet', '-', 'NumberedList', 'BulletedList', 'HorizontalRule', '-', 'Undo', 'Redo'], ], 'extraPlugins': 'codesnippet' } } -
Django+supervisor+daphne: "failed: Error during WebSocket handshake: Unexpected response code: 200"
Currently I built a webssh platform based on django and xterm.js. I am trying to deploy this project on server. However, when I start nginx service, everytime I tried start connection it returned failed: Error during WebSocket handshake: Unexpected response code: 200. I have tried directly run python manager.py runserver 0.0.0.0:8000, daphen -b 0.0.0.0 -p 8001 myproject.asgi:application and supervisord -c /etc/supervisor/supervisord.conf, all of which run successfully. I realize that the problem may be nginx.conf but I don't know where is the problem. can anyone help me about this? my nginx.conf is: upstream wsbackend { server 127.0.0.1:8001; } server { listen 80; server_name leeshen.net www.leeshen.net; client_max_body_size 75M; location /media { alias /srv/http/MyBlog/media; } location /static { alias /srv/http/MyBlog/static; } location / { root /srv/http/MyBlog; uwsgi_pass 127.0.0.1:8000; include /etc/nginx/uwsgi_params; } location /ws { proxy_pass http://wsbackend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } -
How to filter manytomany field values in django restframework
I am trying to query values from model, I want to include manytomanyfield values in query but now I am getting some numbers instead of values, I am using modelviewset in views.py file. I know what have done is wrong, How to do this in right way models.py class TrainingDetailsViewSet(viewsets.ModelViewSet): queryset = TrainingDetails.objects.all().order_by('Name') serializer_class = TrainingDetailsSerializer views.py class TrainingDetails(models.Model): Code = models.CharField(max_length=60) Name = models.CharField(max_length=60) TrainerName = models.ManyToManyField(TrainerDetails, blank=True, related_name='trainer') Agenda = models.FileField() Date = models.ManyToManyField(Date,blank=True, editable= True, related_name='date') Data = models.ManyToManyField(TrainingData, blank=True, related_name='data') def __str__(self): return self.Name serializers.py class TrainingDetailsSerializer(serializers.ModelSerializer): class Meta: model = TrainingDetails fields = ('Code', 'Name', 'TrainerName', 'Agenda' , 'Date' , 'Data' ) I'm getting in response, [ { "Code": "TRA123", "Name": "something", "TrainerName": [ 5, 6 ], "Agenda": "something", "Date": [ 2 ], "Data": [ 2 ] } ] I want, [ { "Code": "TRA123", "Name": "something", "TrainerName": [ 'john' , 'james' ], "Agenda": "something", "Date": [ '19/101/2020' ], "Data": [ 'something' ] } ] `` -
Setting up gunicorn.service [Service] for Django app
Following the documentation and online tutorials on setting up my gunicorn.service results in ModuleNotFoundError: No module named 'my-app' when I run sudo systemctl status gunicorn I realise something is being imported wrong or I do not have the correct directory listed in my gunicorn.service, but I'm struggling to figure out where the issue is regarding the [Service] part. My /etc/systemd/system/gunicorn.service : [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myname Group=myname EnvironmentFile=/home/myname/my-app/my-app/env WorkingDirectory=/home/myname/my-app/my-app/app ExecStart=/home/myname/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ my-app.app.wsgi:application [Install] WantedBy=multi-user.target My directories are as follows: ./ ./ env/ (./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/) .bash_history .bash_logout .bashrc .cache/ .cloud-locale-test.skip .gitconfig .local/ .profile .ssh/ .sudo_as_admin_successful .vim/ .viminfo my-app/ |_ .DS_Store |_ .git/ |_ .idea/ |_ .travis.yml |_ Dockerfile |_ docker-compose.yml |_ env/ (./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/) |_ requirements.txt |_ my_app/ |_ .flake8 |_ db.sqlite3 |_ env |_ manage.py* |_ static/ |_ app/ |_ ./ |_./ |___init__.py |___pycache__/ |_asgi.py |_settings.py |_urls.py |_wsgi.py Also, my settings.py since it might be relevant: from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # … -
Having an issue on my heroku dashboard,various resources are not being loaded for a couple of months now
enter image description here[Heroku wont load resources][1] -
POST method working in POSTMAN but shows error from frontend
I have an api end point that is working fine in POSTMAN but when I try to POST method from frontend axios it gives error JSON detail "Authentication credentials were not provided." from fontend const config = { headers: { "Content-type": "application/json", Authorization : `JWT ${localStorage.getItem("access")}` }, }; axios.post( `...................................`, config, ) But in POSTMAN it works fine with these Authorization enter image description here and Headers enter image description here but in Browser console it shows error with this request enter image description here and for response error enter image description here I know I am adding unnecessary image links here but that's the best way in which I can show my problem.If you need any other details to debug this or If you have any idea why this might be happening? .Please Comment before down voting(it is unclear or not useful). I will really appreciate your help. -
'staticfiles' is not a registered tag library: These solutions don't work
I'm new to Heroku and Django. Now I'm in the middle of Getting Started on Heroku with Python. When I access https://(...secret...)-app-123.herokuapp.com/db, I got the following error: 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz Then I found these solutions. However, these solutions don't solve my problem. Firstly, I changed {% load staticfiles %} to {% load static %} ... in db.html. It gave me: run python manage.py migrate Running python manage.py migrate on ⬢ (...secret...)-app-123... up, run.3361 (Free) Operations to perform: Apply all migrations: admin, auth, contenttypes, hello, sessions Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Since the error message tells me to run manage.py makemigrations, I ran: manage.py makemigrations Traceback (most recent call last): File "C:\Users\xxxxx\python-getting-started\manage.py", line 8, in ? from django.core.management import execute_from_command_line ImportError: No module named django.core.management No module? Django is installed on my machine. I didn't know what to do, so I updated Django on my local machine: C:\Users\xxxxx\python-getting-started>pip install django --upgrade … -
Change pdf filename in Django while downloading
In my admin panel i am uploading a CSV with a certain name and downloading csv in pdf format. but while downloading the pdf the name of downloaded file is static which is given by us that is processed_1 but i want the filename of pdf to be same as of the csv filename while we are uploading csv . PDF function def download_pdf(self, request): # fill these variables with real values csv_file_id = request.GET.get("csv_file_id") try: csv_file = AICSVFile.objects.get(id=csv_file_id) except Exception as e: raise Http404('File not found!') fl_path = get_pdf_file_full_path(settings.MEDIA_ROOT, csv_file.user.id, csv_file_id) filename = 'processed_%s.pdf' % (csv_file_id) try: open(fl_path, 'r') except Exception: raise Http404('File not found!') with open(fl_path, 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=%s" % filename return response raise Http404('File not found!') context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", # "data": data } csv_file_id = request.GET.get("csv_file_id") data = AICSVFileOutput.objects.filter(csv_file_id=csv_file_id) # print(csv_data) context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", "data": data } pdf = render_to_file('pdf/duplicate_defects_org_updated.html', context) # print(pdf) if pdf: response = HttpResponse( pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") filename = "output.pdf" content = "inline; filename='%s'" % (filename) download = request.GET.get("download") if download: content = … -
Django - ImportError: Could not import 'drf_yasg.generators.OpenAPISchemaGenerator' for API setting
I'm trying to add https://github.com/axnsan12/drf-yasg this library to our django application and getting the below error. permission_classes=(permissions.AllowAny,), File "/env/lib/python3.7/site-packages/drf_yasg/views.py", line 67, in get_schema_view _generator_class = generator_class or swagger_settings.DEFAULT_GENERATOR_CLASS File "env/lib/python3.7/site-packages/drf_yasg/app_settings.py", line 122, in __getattr__ val = perform_import(val, attr) File "env/lib/python3.7/site-packages/rest_framework/settings.py", line 166, in perform_import return import_from_string(val, setting_name) File "env/lib/python3.7/site-packages/rest_framework/settings.py", line 180, in import_from_string raise ImportError(msg) ImportError: Could not import 'drf_yasg.generators.OpenAPISchemaGenerator' for API setting 'DEFAULT_GENERATOR_CLASS'. ImportError: cannot import name 'URLPattern' from 'rest_framework.compat' (env/lib/python3.7/site-packages/rest_framework/compat.py). after some research I found some people suggested installing this package to solve the issue pip3 install packaging But this is not making any difference. Any other good api documentation library available for django rest api? -
django attendance system for specific student
i am making attendance system for student but i not getting how i wanted, so looking for your suggestions, i think i'm missing something, i'm not getting list of specific student's attendance in my DetailView just getting one single student attendance, i exactly wanted list of student's attendanc in DetalView, in listView (where show list of subject and from there go in DetailView) i tried with m2m but, it's not possible to specific present and absent days for specific student :( models.py class Student_Attendence(models.Model): lecturer = models.ForeignKey(Lecturer, on_delete=models.SET_NULL, blank=True, null=True) department = models.ForeignKey(to='sis.Department', on_delete=models.SET_NULL, blank=True, null=True) semester =models.ForeignKey(to='sis.Semester', on_delete=models.SET_NULL, blank=True, null=True) subject = models.ForeignKey(to='sis.Subject', on_delete=models.SET_NULL, blank=True, null=True) student = models.ForeignKey(to='sis.Student', on_delete=models.SET_NULL, blank=True, null=True) date = models.DateField(blank=True, null=True) present = models.PositiveIntegerField() absent = models.IntegerField() def get_absolute_url(self): return reverse('lecturer:student_attendence_detail', kwargs={ 'pk': self.pk }) views.py # where show list of subject name class Attendence(generic.ListView): model = Student_Attendence template_name = 'attendence.html' context_object_name = 'queryset' def get_context_data(self, *args, **kwargs): profile = Lecturer.objects.all() semester_course = Student_Attendence.objects.all() context = super().get_context_data(**kwargs) context['profile'] = profile context['test'] = semester_course return context # attendance.html <thead> <tr> <th> No </th> <th> Date </th> <th> Code </th> <th> Subject Name </th> </tr> </thead> <tbody> {% for a in queryset %} <tr class="odd gradeX"> … -
TypeError: topics() missing 1 required positional argument: 'topic_id'
I'm following along a Django tutorial book to make a basic blogging application where users can write journal entries about whatever topic they choose. I've written the url, pattern, view, and template for my topic page but I keep getting this same error. but I think something is wrong with the url pattern. urls.py # Defines url patterns for learning_logs app from django.conf.urls import url from . import views urlpatterns = [ # Home Page url(r'^$', views.index, name='index'), # Topic Main Page url(r'^topics/$', views.topics, name='topics'), # Detail page for a single topic url(r"^topics/(?P<topic_id>\d+)/$", views.topics, name='topic'), ] views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): # This is the home page for our learning_logs app return render(request, 'learning_logs/index.html') # This is the view for 'topics' page 9.5.20 def topics(request, topic_id): '''show a single topic and its entries ''' topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topics.html', context) And the error: TypeError: topics() missing 1 required positional argument: 'topic_id' Any advice? Thank you. -
How to remove object from database on tab close django
I have an image loaded on-page and it's loaded from the database and I want to remove that object from the database when the tab is close how can I do that? framework- Django -
Pipeline - Django social app save image user
I try to save the FB image from my user after a connexion but I got only the url. Any idea about that? If I click on the link of the result, I automatically download the image... so I'm bit lost. models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) image = models.ImageField(default='user/user-30.png',upload_to='user/',null=True,blank=True) full_address = models.CharField(max_length=128) settings.py SOCIAL_AUTH_PIPELINE = ( ... 'user.pipeline.save_image_profile', ) pipeline.py from .models import UserProfile def save_image_profile(backend, user, response, *args, **kwargs): if backend.name == "facebook": if UserProfile.objects.filter(user_id=user.id).exists(): user_object = UserProfile.objects.filter(user_id=user.id)[0] user_object.image = response['picture']['data']['url'] user_object.save() else: UserProfile.objects.create( user=user, image=response['picture']['data']['url'] ) -
How to use library Django-RQL to filter fields of type 'Time' in Django Rest Framework?
I would like using filter in my REST API in my field 'hora' but your type is Time. When I try do query, example: 127.0.0.1:8000/api/v1/queimadas/?hora=17:15:33, the error show: "RQL Parsing error." My task is filter this field 'hora' in beetween of times, like this: ?ge(hora,17:00:00)&le(hora,20:00:00) in url (Following the documentation), but I can not :( Thanks very much all. This is documentation the library django-rql - https://django-rql.readthedocs.io/en/latest/index.html My serializers.py: class QueimadaSerializer(serializers.ModelSerializer): satelite = SateliteSerializer(many=False,read_only=True) cidade = CidadeSerializer(many=False,read_only=True) class Meta: model = Queimada fields = [ 'id', 'latitude' , 'longitude', 'data', 'hora' , 'observacao', 'veracidade', 'visitado', 'satelite', 'cidade' ] My views.py: class QueimadasViewSet(viewsets.ModelViewSet): queryset = Queimada.objects.all() serializer_class = QueimadaSerializer filter_backends = (RQLFilterBackend,) rql_filter_class = QueimadaFilters @action(detail=True,methods=['get']) def satelite(self,request,pk=None): satelite = Satelite.objects.filter(queimada__id=pk) self.pagination_class.page_size = 10 page = self.paginate_queryset(satelite) if page is not None: serializer = SateliteSerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = SateliteSerializer(satelite, many=True) return Response(serializer.data) My filters.py: class QueimadaFilters(RQLFilterClass): MODEL = Queimada SELECT = True FILTERS = ( { 'namespace' : 'cidade', 'filters':('id','nome'), 'qs' : SelectRelated('cidade'), }, { 'filter': 'data', }, { 'filter': 'hora', 'custom': True, 'lookups': { FilterLookups.EQ, FilterLookups.IN, FilterLookups.I_LIKE, FilterLookups.LE, FilterLookups.LT, FilterLookups.GE, FilterLookups.GT }, }, ) -
Call map.setView for javascript from a function with variables
I am running a django app with tables2. I then set up a field with linkify where i want to zoom to a feature by running a javascript function. My code in the renderd htm is: <div id="map" class="leaflet-container-default"></div> ...... <td ><a href="javascript:onclick=myFunction(7.22591038,61.1982749)">Zoom til</a></td>.... <script type="text/javascript"> function myFunction(lat,long) { map.setView([lat,long], 15); } </script> -
Django dumpdata fails on special characters
I'm trying to dump my entire DB to a json. When I run python manage.py dumpdata > data.json I get an error: (env) PS C:\dev\watch_something> python manage.py dumpdata > data.json CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefined> Exception ignored in: <generator object cursor_iter at 0x0460C140> Traceback (most recent call last): File "C:\dev\watch_something\env\lib\site-packages\django\db\models\sql\compiler.py", line 1602, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. It's because one of the characters in my DB is a sepcial character. How can I dump the DB correctly? FYI, all other DB functionalities work fine -
Specify action in API request - Django Rest framework
I have different serializers for List and Detail actions. By default an API has an action - List. How do I specify the action? -
Page 2 elements not clickable after implementing infinite scroll in Django
I used waypoints to implement an infinite scroll by follow this guide. The infinite scroll works fine but for some reason, page 2 elements are not clickable while page 1 elements are clickable. In other words the page loads and works fine until I scroll down to page 2 and suddenly all the "href" and other clickable elements are no longer clickable. Here is my code. <div class="mt-5 ads_container"> <div class="container-fluid infinite-container"> {% for ad in ad_list %} {% if forloop.counter0|divisibleby:4 %} <div class="row infinite-item"> <div class="col-sm-12"> <div class="latest-magazine clearfix"> <div class="latest-ads-space clearfix"> {% endif %} <div class="late-ad"> <div class="inner"> <a href={% url 'advert' ad_pk=ad.id %}> <!-- <img data-src="{{ ad.profile_pic }}" class="img-responsive lazyloaded"--> <!-- src="{{ ad.profile_pic }}"/>--> <div class="pic_div" style="background-image: url({{ ad.profile_pic }}); background-size: contain; background-repeat: no-repeat; background-position: center;"></div> </a> <div class="p-a" style="height: 70px;"> <em>{{ ad.Ad_title|capfirst|shorten_title }}</em> <div class="clearfix"> <em></em> <em class="text-success">R{{ad.price}}</em><em> {% timezone "Africa/Johannesburg" %}{{ ad.date_created|timesince }}{% endtimezone %}</em> </div> </div> </div> </div> {% if forloop.counter0|add:"1" in break_pts or forloop.counter0|add:"1" == ad_list|length %} </div> </div> </div> </div> {% endif %} {% endfor %} </div> {% if ad_list.has_next %} <a class="infinite-more-link" href="?page={{ ad_list.next_page_number }}"></a> {% endif %} <div class="d-flex justify-content-center" style="display:none;"> <div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> </div> … -
Django convert local time to utc time
This is my code using this i am converting my time to in utc time : pickup_time = "03:00 PM" local_time = pytz.timezone("Asia/Kolkata") naive_datetime = datetime.datetime.strptime (pickup_time, "%I:%M %p") local_datetime = local_time.localize(naive_datetime, is_dst=None) utc_datetime = local_datetime.astimezone(pytz.utc) print(utc_datetime) print(utc_datetime.strftime("%I:%M %p")) In result i am getting like : 1900-01-01 09:07:00+00:00 09:07 AM but according to me it should be 09:30 AM .in IST offset of UTC+05:30 but i am getting 6 hours. can anyone please suggest me what i am doing wrong here . -
How to filter option in Django?
i have 3 models involved in this issue Category, Survey and Question Category.py from django.db import models from django.utils.translation import gettext_lazy as _ class Category(models.Model): name = models.CharField(_("Name"), max_length=400) description = models.CharField(_("Description"), max_length=2000, blank=True, null=True) class Meta: verbose_name = _("category") verbose_name_plural = _("categories") def __str__(self): return self.name def slugify(self): return slugify(str(self)) Survey.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.urls import reverse from django.conf import settings from django.utils.timezone import now # from .category import Category # Create your models here. class Survey(models.Model): ALL_IN_ONE_PAGE = 0 BY_QUESTION = 1 BY_CATEGORY = 2 DISPLAY_METHOD_CHOICES = [ (BY_QUESTION, _("By question")), (BY_CATEGORY, _("By category")), (ALL_IN_ONE_PAGE, _("All in one page")), ] name = models.CharField(_("Name"), max_length=400) description = models.TextField(_("Description")) is_published = models.BooleanField(_("Users can see it and answer it"), default=True) editable_answers = models.BooleanField(_("Users can edit their answers afterwards"), default=True) display_method = models.SmallIntegerField( _("Display method"), choices=DISPLAY_METHOD_CHOICES, default=ALL_IN_ONE_PAGE ) category = models.ManyToManyField("Category", verbose_name=_("Category"), blank=True, related_name="surveys") template = models.CharField(_("Template"), max_length=255, null=True, blank=True) publish_date = models.DateField(_("Publication date"), blank=True, null=False, default=now) class Meta: verbose_name = _("survey") verbose_name_plural = _("surveys") @property def safe_name(self): return self.name.replace(" ", "_").encode("utf-8").decode("ISO-8859-1") def latest_answer_date(self): """Return the latest answer date. Return None is there is no response.""" min_ = None for response in self.responses.all(): if … -
why is this error coming "Unexpected EOF" ? in my django- Ajax project
I'm trying to make a django sheet there using ajax so that I can change it without refreshing the page. but I faced such a problem Unexpected EOF, and I don't know what to do. and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and andand and and and and and and and and and and and and and and and and and and and it is base.html file: … -
Queryset AttributeError: the 'dict' object has no attribute '_meta'
models.py class keywords(models.Model): user = models.ForeignKey(User,related_name="users",on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add = True) searchedword = models.CharField(max_length=50) class keywordsProxy(keywords): class Meta: proxy = True admin.py @admin.register(keywordsProxy) class keywordsProxyAdmin(admin.ModelAdmin): list_display = ('searchedword','get_cword') def get_queryset(self, request): qs = super().get_queryset(request) return qs.values('searchedword').annotate(cword=Count('searchedword')) def get_cword(self, instance): return instance.cword get_cword.short_description = "count" I want to display count of searched words like this: searchedword count python 3 java 2 . . . . . . But I got : 'dict' object has no attribute '_meta' if I change query to: return qs.annotate(cword=Count('searchedword')) or return keywordsProxy.objects.all().annotate(cword=Count("searchedword")) result will be not correct: searchedword count python 1 python 1 python 1 java 1 java 1 Any help on how to solve this is welcome. Thank you in advance -
Django DRY - How to extend two .html files inside a Django Template?
What do I want? I want to extend cards/apps.html inside addstudents.html so that I don't need to write the chucks of codes multiple times. What can I do to extends multiple .html files inside DJANGO template? Error I am getting 'extends' cannot appear more than once in the same template WHAT TO DO? NOTE: I don't want to use {% include %}, because the situation/condition isn't suitable. SOME INFORMATION YOU MAY NEED... Inside cards/apps.html <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">{{card_title}}</h6> </div> <div class="card-body"> {% block card_body %} {% endblock %} </div> Inside addstudents.html {% extends 'layouts/panel.html' %} {% extends 'apps/card.html' %} {% load static %} {% block content %} {% with card_title='My Card TITLE' %} {% block card_body %} ...SOME FORM, .... SOME PARAGRAPH {% endblock %} {% endblock %} What's inside layouts/panel.html layouts/panel.html contains some menu and navbars items [including CSS, bootstrap and JS dependencies]. What's apps/card.html? apps/card.html contains the code-snippet of HTML and Bootstrap CARD. And I don't want to write this code multiple times. That's why I want it to be manipulated via Django Template Tags. HOPE YOU UNDERSTOOD -
How to disabled field with if-else condition in JS
I have a problem on disabled input field on certain condition. In this case, user can add multiple row in a form. But, the number of row is greater than four, then some of the field will be disabled. Here my segment of JavaScript. In order to know the number of row already exceed or not, I check using index number. But the problem is, the code seems like didn't check the if-else condition. var valIndex =0; for (var i=0, formCount=forms.length; i<formCount; i++) { valIndex = i+1; $(forms.get(i)).find('.assign_label_number').text(" - " + valIndex + nth(valIndex)); console.log(valIndex); document.getElementById("gift").addEventListener("click", function(){ var gift = $(forms.get(i)).find('input[id^=id_Phone1][id$=less_tax_examption]'); if(valIndex => 4){ console.log('disabled') gift.prop("disabled", true); } else{ console.log('enable') gift.prop("disabled", false); } }); }); Actually it work just fine if I remove the document.getElementById. But since there is few field with different condition, so I need to differentiate each of the button by Id. I already tried to used .attr("disabled", true) also didn't work Please correct me if I'm wrong. Thank you in advanced for your help and time. -
load content of one HTML template on div of another HTML template using DJANGO
am new to django concept , so i want to include one html template inside div of another html template . i tried using iframe but when i load the page it says localhost refused to connect , then i referred some of the stack answers and i did it with include but when i give include the page is not loading . IndexPage.html <section id="testimonial" class="testimonial section-padding"> <div class="overlay"></div> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-7 col-md-12 col-sm-12 col-xs-12"> <div id="testimonials" class="owl-carousel wow fadeInUp" data-wow-delay="1.2s"> <div class="item"> <div class="testimonial-item"> <div class="info"> <!-- <iframe id="encoder_iframe" height=75% width="50%" src='/templates/index.html'></iframe> --> {% include "index.html" %} </div> </div> </div> </div> </div> </div> </section> index.html {% extends 'base.html' %} {% block content %} <h1 class="page-header"></h1> <p class="lead"></p> <p class="lead"><a href="/products">Customer ListList</a>.</p> {% endblock %} so have to include index.html inside div of indexpage.html structure of folder