Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up OSRM on Heroku
Making a new thread for this post Setting up OSRM (Open Source Routing Machine) on Heroku because it's been 6 years and the older buildpacks don't seem to work, at least for me. Has anyone had recent success setting up OSRM in their Heroku apps? I've tried several different ways over the last couple days but nothing has worked. My situation may be specific because I already have a django heroku app and want to run OSRM inside so I can access it from the local host. I've tried using the following buildpacks separately, and they each fail when I try to push my code. I think they're just not maintained and outdated by now. https://github.com/chrisanderton/heroku-osrm-buildpack https://github.com/jpizarrom/osrm-heroku I currently already use the two below buildpacks and have added the osrm ones on top: https://github.com/heroku/heroku-geo-buildpack.git heroku/python [one of the osrm buildpacks] I was thinking that maybe there's no recent literature on setting up OSRM on Heroku because Heroku Docker is much easier to use now. But I've also tried setting up OSRM with Heroku Docker and failed. I would like to run the docker image inside my current app, but my app doesn't use Heroku's container stack. And I've also been … -
How to show data from cluster done by using k means on website
I have categoriesed cricket player using k-means clustering but now not able to show that particular player belongs to which category in my Website using html and django can anyone help -
In Django bootstrap project toast messages showing for the first card in loop element
I want to toast messages for all those cards. but it is showing for the first card only. I have attached a view of my page where I want to add a toast message to view the details of the card if a user is not logged in. ![Text]https://i.stack.imgur.com/cYSPW.jpg) document.getElementById("toastbtn").onclick = function() { var toastElList = [].slice.call(document.querySelectorAll('.toast')) var toastList = toastElList.map(function(toastEl) { return new bootstrap.Toast(toastEl) }) toastList.forEach(toast => toast.show()) } <section class="details-card"> <div class="container"> <div class="row"> {% for homes in home %} <div class="col-md-4 mb-4"> <div class="card-content"> <div class="card-img"> <img src="{{ homes.coverImg.url }}" alt="Cover Image"> <span><h4>{{ homes.pricePerMonth }}Taka</h4></span> </div> <div class="card-desc"> <p class="small mb-1"> <i class="fas fa-map-marker-alt mr-2"></i>{{homes.address}}</p> <h3>{{ homes.title}}</h3> {% if request.user.is_authenticated %} <a href="{% url 'HomeDetails' homes.id %}" class="btn btn-md btn-primary hover-top">Details</a> {% else %} <button type="button" class="btn btn-primary" id="toastbtn">XDetails</button> {% endif %} </div> </div> </div> {% endfor %} </div> </div> </section> <!-- Alert Message Popup--> <!--bottom-0 end-0 p-3--> <div class="position-fixed top-50 start-50 translate-middle p-3" style="z-index: 11"> <div id="liveToast" class="toast hide" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img src="({% static 'img/icon.png' %})" class="rounded me-2" alt="..."> <strong class="me-auto">My Second Home</strong> <small>0.1s ago</small> <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body"> Hello!<br>You need to login first to see details. <div class="mt-2 … -
Ajax with knockout form is not working in django
productscreate.html <form> <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image"></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: mySubmit">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> var formData1 = new FormData(); $(document).on('click', '#submit',function(e){ e.preventDefault() var viewModel = { title:ko.observable(),description:ko.observable(), mySubmit : function(formElement) { var formData = { 'title' : viewModel.title() , 'description' : viewModel.description(), }; formData1.append('image', $('#image')[0].files[0]) $.ajax({ type: "POST", url: '{% url "productscreate" %}', data: formData,formData1, cache: false, processData: false, enctype: 'multipart/form-data', contentType: false, success: function (){ window.location = '{% url "productslist" %}'; }, error: function(xhr, errmsg, err) { console.log(xhr.status + ":" + xhr.responseText) } }); } }; ko.applyBindings(viewModel); </script> views.py class ProductsList(ListView): model = products context_object_name = 'products' template_name = "productslist.html" class ProductsCreate(CreateView): model = products fields = ['title','description','image'] template_name = "productscreate.html" success_url=reverse_lazy('productslist') class ProductsDetailView(DetailView): template_name = "productsdetail.html" queryset = products.objects.all() context_object_name = 'products' model = products Ajax with knockout is not working in this project I want to submit the form with help of ajax with knockout js code Now when i click submit button form value is not submitting. I want to submit form with ajax I don't know … -
how can we add data into database using migration files in django?
I am currently using Django 3.2 i wanted to add data to Database using migration files. from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sbimage', '0001_initial'), ] operations = [ migrations.CreateModel( name='AuthNumberR', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('auth_number_r', models.CharField(max_length=64)), ], ), migrations.RunSQL("INSERT INTO AuthNumberR (id, auth_number_r) VALUES (2, 'c');"), ] is this the proper way to insert data? -
Is there a proper design pattern for this situation?
I'm building a simple crud app in Django which is basically enhanced reporting for commerce related software. So I pull information on behalf of a user from another software's API, do a bunch of aggregation/calculations on the data, and then display a report to the user. I'm having a hard time figuring out how to make this all happen quickly. While I'm certain there are optimizations that can be made in my Python code, I'd like to find some way to be able to make multiple calculations on reasonably large sets of objects without making the user wait like 10 seconds. The problem is that the data can change in a given moment. If the user makes changes to their data in the other software, there is no way for me to know that without hitting the API again for that info. So I don't see a way that I can cache information or pre-fetch it without making a ridiculous number of requests to the API. In a perfect world the API would have webhooks I could use to watch for data changes but that's not an option. Is my best bet to just optimize the factors I control to … -
when creating a record an error is declared: NOT NULL constraint failed: faq.user_id but the user was declared in views
As you can see form.user = request.user is declared after p fom.save(commit=false), but the error persists. can anybody help me? either with request.user or without request.user the error persists. remembering that I'm logged in as admin, and in /admin the functionality works correctly, inserting null=True creates the record but the functionality is not correct. models.py from django.db import models from django.utils import timezone from .. import settings class Faq(models.Model): CAT_FAQ_CHOICES = ( (0, 'Selecione'), (1, 'FAQ Todos'), (2, 'FAQ Psicologo'), (3, 'FAQ Paciente'), (4, 'FAQ Empresa'), ) idfaq = models.AutoField(primary_key=True) titulo = models.CharField( verbose_name='Titulo da Dúvida', max_length=100, null=False, blank=False) descricao = models.TextField( verbose_name='Descrição', null=True, blank=True) data_cadastro = models.DateTimeField( verbose_name='Data de Cadastro', auto_now=True) is_active = models.BooleanField('Ativado | Desativado', default=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tipofaq = models.IntegerField(choices=CAT_FAQ_CHOICES,default=0) def __str__(self): return self.titulo class Meta: db_table = 'faq' verbose_name = 'faq' verbose_name_plural = 'faqs' views.py @login_required def criar_faq(request): if request.user.is_paciente: form = FaqForm(request.POST or None, initial={ 'user': request.user.paciente, 'tipofaq': 3}) custom_template_name = 'area_pacientes/base_paciente.html' if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('faq:listar_faq') else: print(form.errors) return render(request, 'area_administrativa/faq/novo-faq.html', {'form': form, 'custom_template_name': custom_template_name}) elif request.user.is_psicologo: form = FaqForm(request.POST or None, initial={ 'user': request.user.psicologo, 'tipofaq': 2}) custom_template_name = 'area_psicologos/base_psicologo.html' if form.is_valid(): form = form.save(commit=False) form.user … -
Django model with a type field and lots of custom logic
I have a Django model that has a type field: class MyModel(models.Model): type = models.CharField(choices=MyModelTypes.choices) ... def some_func(self): if self.type == "TYPE_1": do_something_1() elif self.type == "TYPE_2": do_something_2() This is getting really complicated and is causing conditionals to be littered everywhere, so I'm wondering if there's some way to cast my model into some specific object that has a specific implementation of that some_func() function for the type.: class MyModelTypeA: ... class MyModelTypeB: ... class MyModel(models.Model): type = models.CharField(choices=MyModelTypes.choices) ... def some_func(self): # Obviously this won't work, but I want something that allows me to turn # MyModel into the right type then call the `some_func()` (which has logic # specific to the `type`). MyModelType(self).some_func() Or maybe that's the wrong approach. Any ideas? -
When Django Form is Invalid, why only file type input is rest?
If there is an invalid field after submitting my Django Form, the other fields have input values when submitted, but only the inputs of the file type will be emptied. I don't think there's anything to change in Dajngo. Perhaps this is a characteristic of html file type input? For example, my form compresses video files uploaded by users. And it takes quite a bit of time. If something goes wrong after submitting the form, the user must select the file again and proceed with the compression process. This is not good. Forms.py class VideoArtUploadForm(forms.ModelForm): class Meta: model = models.VideoArt fields = ( "video", "thumbnail", "poster", "title", "year", "artist", "description", ) widgets = { "video": forms.FileInput(attrs={"accept": "video/mp4"}), "title": forms.TextInput(attrs={"placeholder": "Il titolo del video"}), "year": forms.TextInput( attrs={"placeholder": "l'anno in cui il video è uscito"} ), "artist": forms.TextInput(attrs={"placeholder": "Il nome di artista"}), "description": forms.Textarea( attrs={"placeholder": "una descrizione del video "} ), } def clean_thumbnail(self): thumbnail = self.cleaned_data.get('thumbnail') if thumbnail: if thumbnail.size > 10*1024*1024: raise forms.ValidationError("Thumnail si deve essere meno di 10MB") return thumbnail else: raise forms.ValidationError("Thumnail è necessario") def clean_poster(self): poster = self.cleaned_data.get('poster') if poster and (type(poster) != str): if poster.size > 10*1024*1024: raise forms.ValidationError("Cover image si deve essere meno di 10MB") … -
How best to validate number of total reverse relationships before saving
I have an Item model that is reverse-related to two other models (ItemComponent and or ItemComponentCategory). The idea is I'd like to be able to validate that Items have no more than 4 relations to the two other models, combined, before being saved. class Item(models.Model): name = models.CharField(max_length=40, unique=True) class ItemComponent(models.Model): parent_item = models.ForeignKey(Item, related_name='components') class ItemComponentCategory(models.Model): parent_item = models.ForeignKey(Item, related_name='categories') I'd like to create a validation that raises an error before saving either the Item, ItemComponent, or ItemComponentCategory objects if the saved objects will result in > 4 object relations between them. I have tried adding something like this to the clean methods for all three: def clean(self): if (self.parent_item.components.count() + self.parent_item.categories.count()) > 4: raise ValidationError(_(f'Items can have no more than 4 components and/or component categories')) This seems to work as long as the Items and their relations are already saved and you're trying to add more relations. However, if I create a TabularInline in the ItemAdmin to add these 'sub types,' if you will.. I can create a new Item and add as many of these sub types and save it no problem. What am I missing here? -
Django SelectDateWidget
date_range = 100 this_year = date.today().year birth_date= forms.DateField(label='What is your birth date?', widget=forms.SelectDateWidget(years=range(this_year - date_range, this_year+1))) I would like to only select dates 100 years from today. But I currently can get values like Dec 31 2021 where sometimes the months and days don't match the correct values. -
Convert text to list of Strings Python
How can i convert these lines in a .txt file into a list of strings (each list item is a row in the text file): great dane saint bernard, st bernard eskimo dog, husky malamute, malemute, alaskan malamute siberian husky the code I did does the split , but make no consideration for the comma! Meaning , I want to split based on the comma , not only the line. This is the code I did. with open(dogfile) as file: lines = file.readlines() dogs_list = [line.rstrip() for line in lines] -
Django returning "CSRF verification failed. Request aborted. " behind Nginx proxy locally
I'm running a simple Django application without any complicated setup (most of the default, Django allauth & Django Rest Framework). The infrastructure for running both locally and remotely is in a docker-compose file: version: "3" services: web: image: web_app build: context: . dockerfile: Dockerfile command: gunicorn my_service.wsgi --reload --bind 0.0.0.0:80 --workers 3 env_file: .env volumes: - ./my_repo/:/app:z depends_on: - db environment: - DOCKER=1 nginx: image: nginx_build build: context: nginx dockerfile: Dockerfile volumes: - ./my_repo/:/app:z ports: - "7000:80" ... # db and so on as you see, I'm using Gunicorn the serve the application and Nginx as a proxy (for static files and Let's Encrypt setup. The Nginx container has some customizations: FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d And the nginx.conf file is a reverse proxy with a static mapping: server { listen 80; location / { proxy_pass http://web; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /app/my_repo/static/; } } Running this on the server after setting up let's encrypt in the Nginx container works without any issue, but locally I get the "CSRF verification failed. Request aborted." error every time I submit a form (e.g. create a dummy user in Django Admin). I … -
Updating admin/staticfiles with Django
I am having trouble with updating the css, img, fonts, and js admin files when I upgrade Django. I first noticed this when I upgraded to Django 2.0 (see here), and now the problem is worsening as I upgrade to 4.0. The backend functionality is working perfectly well. But now when I access the admin console, the homepage remains on the top of the browser page, even when I navigate to different models. I noticed that none of the /static/admin/ files (css, js, img, fonts) were updated on my local machine when upgrading from Django 2.2.24 to 4.0. Should I have expected these files to update along with Django? Am I missing a step to ensure that the admin static files are updated to reflect the newest version of Django? -
How to create a dynamic dependent form select options data model in django
I am new to django. I'm trying create an ecommerce application in which the user will select from a category of options [automobile, property, electronics, phones, clothes etc], and upon selecting an option (say automobile), the next select field options will be populated asking for model [Honda, Toyota, Chrysler etc], if user select say Toyota, a list of Toyota models comes up [Camry, Highlander, Corolla, etc.], upon selecting say Camry, another set of options comes up asking for year, and so on. How do I implement (generate and/or store) this type of data using django models? I'll be very grateful for a swift response to this. Thank you. -
Why DRF shows Forbidden (CSRF cookie not set.) without @api_view(['POST'])?
I'm using django-rest-framework(backend) and react(frontend). In react i created a login form ,when i submite the form it sends an axios.post to my view function. The problem is django raise a error and the message: Forbidden (CSRF cookie not set.) My axios: axios({ method:'post', url: url, data:{email:email, password1:senha}, headers: {'X-CSRFTOKEN': token}, withCredentials: true }) .then((response)=>{ console.log(`Reposta: ${response.data}`) }) .catch((error)=>{ console.log(`Erro: ${error.data}`) }) My django view: def login_usuario(request): if request.method == 'POST': return HttpResponse('Something') Obs1:If i include de @api_view(['POST']) decorator works, but i want to know if is possible make the request without it. Obs2: When my react form render, a function that creates a csrf_token was called, so the csrf_token its being sent but django isn't reading it -
Python - "cannot unpack non-iterable int object" when importing json data into database
I'm working on an importer to import a list of facilities from a json file into my database. The importing works. But when i added some extra conditions to update existing facilities (whenever i run the script again and there is updated data inside the json) it stopped working the way it originally did. The updating works if i only have 1 facility inside the json file but if i add more than one i get the following error: cannot unpack non-iterable int object Also: Instead of updating it will just create two additional copies of one of the facilities. Been trying to figure this out for a couple of days now but so far no luck. import_facility_from_file.py import os import json from data_import.models import Facility, FacilityAddress, FacilityInspectionInfo, FacilityComplaints from django.core.management.base import BaseCommand from datetime import datetime from jsontest.settings import BASE_DIR, STATIC_URL class Command(BaseCommand): def import_facility_from_file(self): print(BASE_DIR) data_folder = os.path.join(BASE_DIR, 'import_data', 'resources') for data_file in os.listdir(data_folder): with open(os.path.join(data_folder, data_file), encoding='utf-8') as data_file: data = json.loads(data_file.read()) for key, data_object in data.items(): UUID = data_object.get('UUID', None) Name = data_object.get('Name', None) IssuedNumber = data_object.get('IssuedNumber', None) Capacity = data_object.get('Capacity', None) Licensee = data_object.get('Licensee', None) Email = data_object.get('Email', None) AdministratorName = data_object.get('AdministratorName', None) TelephoneNumber = … -
Python Package Download in offline environment :( ('typing_extensions-4.0.1')
I'm trying to run a Django Application in an offline internal network environment. I have a problem in the process of downloading requirements for this. Currently, I'm installing Python packages using the 'setup.py install' command. However, there is no setup.py file in the 'typing_extensions-4.0.1' package, so it's impossible to download the package. I want to ask for advice on how to solve it. For your information, 'conda', 'pip' conmmands are not available. -
Django - UnboundLocalError: local variable 'image_link' referenced before assignment
I have written a function for parsing news articles feeds. def save_new_articles(feed, source_id, category_id): channel_feed_title = feed.channel.title.title() channel_feed_link = feed.channel.link channel_feed_desc = feed.channel.description official_source_id = source_id post_category_id = category_id for item in feed.entries: parsed_summary = item.summary soup = BeautifulSoup(parsed_summary, 'lxml') images = soup.findAll('img') for image in images: image_url_link = (image['src']) if image_url_link is not None: image_link = image_url_link else: image_link = "https://www.publicdomainpictures.net/pictures/280000/velka/not-found-image-15383864787lu.jpg" parsed_title = item.title formatted = re.sub("<.*?>", "", parsed_title) post_title = formatted post_link = item.link description = item.description output_summary = re.sub("<.*?>", "", description) title = item.title capital = title.title() tags = capital.split() date_published = parser.parse(item.published) if not Posts.objects.filter(guid=item.guid).exists(): post = Posts( title = post_title, link = post_link, summary = output_summary, image_url = image_link, tags = tags, pub_date = date_published, guid = item.guid, feed_title = channel_feed_title, feed_link = channel_feed_link, feed_description = channel_feed_desc, source_id = official_source_id, category_id = post_category_id ) post.save() else: logger.info("Duplicate Post Detected! Skipping...") But upon running the code I get: image_url = image_link, UnboundLocalError: local variable 'image_link' referenced before assignment I don't understand where the error is coming from seeing as I had defined image_link in the image for loop statement above. I have checked similar answers on SO but I don't seem to find a suitable answer. … -
Django: using AJAX for login, how do (should) I update a form's CSRF Token?
Context: A company project I am working on is using AJAX to log a user in for certain actions on the webpage. This webpage can be viewed without logging in, but certain actions need authentication (like updating the settings of a piece of hardware). I want to preserve the form the user currently has so they don't have to re-input their changes (which I am currently doing by hiding the form and overlaying a "login" form) so refreshing the page is not an option, or at the very least, a last resort. The issue: After the login has completed, the CSRF token of the first form is now invalid and needs to be updated. This is not a question of "how do I add a CSRF token to an AJAX request", but a "how do I update it". Django is throwing the following error after logging in: Forbidden (CSRF token from POST incorrect.) Here's what I've already tried: Sending a new CSRF token for the form after logging in (server-side): form = AuthenticationForm(data=request.POST or None) if form.is_valid(): # Login the user user = authenticate( username=form.cleaned_data.get("username"), password=form.cleaned_data.get("password"), ) if user is not None: login(request, user) # Neither of these have worked … -
Django Multi Step Form
Currently my sign up for all users is currently working but I want to add 2 buttons before it that will sign up differently based off which element they clicked. Use normal sign up if it's User and use another for Doctor. 2 users: Doctor and User. <html> <body> <button>Doctor</button> <button>User</button> </body> </html> models.py: is_doctor -> a boolean has_credentials -> verifies doctor a file upload -> wants admin to verify before adding signup.html(displays on http://localhost:8000/signup/) {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> <a href="{% url 'login' %}">Log In</a> </form> {% endblock %} views.py from django.shortcuts import redirect, render from .forms import SignUpForm, UserProfileForm from django.contrib.auth import login, authenticate def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) forms.py from django import forms from django.core.files.images … -
Django and Jquery Autocomplete Issues
I know there are several posts regarding autocomplete and django, but I'm recently entering in to the realm of jquery and somehow I'm lost. As you can imagine, I need an autocomplete for the following field: HTML file <div class="ui-widget"> <input name="user_name"class="form-control "id="company-search"> </div> <script type="text/javascript"> $(function() { $("#company-search").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 1, }); }); </script> URL path('autocomplete/',views.autocomplete, name='autocomplete') Views def autocomplete(request): data = request.GET['term'] forecast = LeadEntry.objects.select_related('lead_id') companies = [str(i.lead_id.company).lower() for i in forecast] search = [i for i in companies if i.startswith(data.lower()) ] result = [] for company in search: data = {} data['label'] = company data['value'] = company result.append(data) print(json.dumps(result)) mimeetype='application/json' return HttpResponse(json.dumps(result),mimeetype) Please note that the ajax portion works well, I can see the view working every time, I type a new letter, I'm getting a json file with the correct data. My real struggle is that I can't display it in my HTML, how do I send back that data an added to the same field, ideally, I want to be able to get a drop down list? I'm getting the following errors on the javascript side: Regards -
django - custom storage url
I have a dropbox storage class inheriting Storage (see below). The thing is url method is going to run on each image render, causing back and forth to Dropbox API which seems kind of unnecessary. Would it be correct to instead move the shared link functionality in _save instead and store the URL in the name attribute (varchar in DB) and leave url() blank? class DropboxStorage(Storage): def __init__(self, options=None): if not options: options = settings.CUSTOM_STORAGE_OPTIONS self.d = dropbox.Dropbox(options['DROPBOX_KEY']) def _open(self, name, mode='rb'): with open(name, mode=mode) as f: return File(f, name) def _save(self, name, content): meta = self.d.files_upload( content.read(), f'/Images/{name}', autorename=True) return meta.name def url(self, name): link_meta = self.d.sharing_create_shared_link(f'/Images/{name}') return link_meta.url.replace('dl=0', 'raw=1') # no need to implement since files_upload will take care of duplicates def exists(self, name): return False -
How to pass data on django ajax?
how to pass filter data from Django model/view to ajax? I tried to pass the data but, it's showing no result. The ajax return field is blank. From the request get method I tried to post the data, that's working fine. With the ajax method, I tried to do as follows, but it's throwing just a blank area. I tested on console, the filter value is correctly passed to views but from views, it's not fetching correctly. Is it an ajax success problem or do my views has any other issue? Please help me My HTML: <ul class="widget-body filter-items "> {% for categories in categories%} <li class = "sidebar-filter " data-filter="category" data-value="{{categories.id}}" ><a href="#">{{categories.name}}</a></li> {% endfor %} </ul> <div class="product-wrapper row cols-lg-4 cols-md-3 cols-sm-2 cols-2"> {% for product in products%} <div id = "product-wrapper" class="product-wrap product text-center"> {{product.name}} {% endfor%} </div> </div> Ajax: $(document).ready(function () { $('.sidebar-filter').on('click', function () { var filterobj= {}; $(".sidebar-filter").each(function(index, ele){ /**var filterval = $(this).attr('data-value');*/ /**var filterval = $(this).value=this.attr('title');*/ /**var filterval = $(this).val($(this).text());*/ var filterval=$(this).data("value"); var filterkey = $(this).data('filter'); filterobj[filterkey]= Array.from(document.querySelectorAll ('li[data-filter=' + filterkey+'].active')).map(function(el){ /**return $(el).data("value");*/ return $(el).data("value") /** return el.getAttribute('data-value');*/ }); }); console.log(filterobj) $.ajax ({ url:"/products/filter-data", data:filterobj, datatype:'json', success:function(res){ console.log(res.data) var bodyOnly = $(res.data).find('.product-wrapper').html(); $('.product-wrapper').html(bodyOnly); … -
Is the implementation of Django code into HTML possible?
HTML File: <script> from django.contrib import messages messages.error('Sign-In First') </script> This doesn't work but is there a way where I can do this? Because my layout of an error message is not appealing as compared to Django's.