Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
apache2 ubuntu django : ModuleNotFoundError: No module named 'encodings'
i tried to upload my django 2.2 project but u get this error while i type : cat /var/log/apache2/error.log the error is: (13)Permission denied: mod_wsgi (pid=7692): Unable to stat Python home /root/project_name/venv/. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' and this is my /etc/apache2/sites-available/django_proj.conf <VirtualHost *:80> Alias /static /root/project_name/static <Directory /root/project_name/static> Require all granted </Directory> Alias /meida /root/project_name/meida <Directory /root/project_name/meida> Require all granted </Directory> <Directory /root/project_name/zettapc> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /root/project_name/project_name/wsgi.py WSGIDaemonProcess django_app python-path=/root/project_name python-home=/root/project_name/venv/ WSGIProcessGroup django_app </VirtualHost> is there something i've missed , or doing something wrong please? ubuntu 18lts , mysql, django =2.2 -
Django: Pass UserID to settings.py
I need to pass the UserID to settings.py because of this line: FROALA_UPLOAD_PATH = os.path.join(BASE_DIR, 'media/froala_editor/', instance.user.id) -
Django CBV detailview get_context_data not passing id to the query
class Project(models.Model): name = models.CharField(max_length=256, unique = True ) location = models.CharField(max_length=256,blank=True, default='') type = models.CharField(max_length=100,blank=True, default='') floors = models.CharField(max_length=100,blank=True, default='') creationdate = models.DateTimeField(auto_now_add=True) class Flat(models.Model): FACING_CHOICES = [ ('east', 'East'), ('west', 'West'), ('north', 'North'), ('south', 'South'), ] STATUS_CHOICES = [ ('sold', 'Sold'), ('available', 'Available'), ('mortgage', 'Mortgage'), ] project = models.ForeignKey('Project', on_delete=models.CASCADE) flatno = models.PositiveSmallIntegerField(null=True) flatarea = models.PositiveSmallIntegerField(null=True) facing = models.CharField(max_length=5, choices=FACING_CHOICES, default='east') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='available') Views.py class ProjectDetailView(DetailView): model = Project template_name = 'projects/project_detail.html' def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) context['totalavailable_flats'] = Flat.objects.filter (project_id = self.kwargs.get('id')) .count() return context template projects/project_detail.html {% extends '_base.html' %} {% block content %} {% load static %} <p>{{ project.finishdate }}</p> <p>Available flats : {{ total_flats }}</p> {% endblock content %} How to pass the Project_id to the query to get flat details Query - Project id not passing to the query SELECT COUNT(*) AS "__count"enter code here FROM "projects_flat" WHERE "projects_flat"."project_id" IS NULL My view not passing project id to the query. -
How to group and filter objects by list objects
I have to get average grade value by each type of question(many grades at 1 question, 1 question at 1 grade). Below my code to get just all grades which user got but i don't know how to "group by" grades by question and why my filter doesn't work(returning 400 bad request) @action(detail=False, methods=['post']) def results(self, request): user_id = request.data["user_id"] survey_id = request.data["survey_id"] self_rating_objects = Grade.objects.filter(interview__in=Interview.objects.filter( survey_id=survey_id, target_user_id=user_id)) serializer = GradeSerializer(data=self_rating_objects,many=True) if serializer.is_valid(): return Response(serializer.data,status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) Here my grade model class Grade(models.Model): created_at = models.DateField(auto_now_add=True) value = models.IntegerField() question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") interview = models.ForeignKey(Interview, on_delete=models.CASCADE, related_name="grades") And interview model class Interview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="users") target_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="target_users") comment = models.TextField(default='') created_at = models.DateField(auto_now_add=True) survey = models.ForeignKey(Survey, on_delete=models.CASCADE, related_name="interviews") -
How to store the Json in a Django Db as text
I am sending a POST request from my front-end from which I want to save the JSON into my database as a text field I am using django rest framework and sqlite db. My serializer class is class DataSerializer(serializers.Serializer): json_data = serializers.JSONField() def create(self,validated_data): return TableUser.objects.create(json_data=validated_data) and my model is class TableUser(models.Model): username = models.TextField(default="unlogged") json_data = models.TextField() When i send the POST request it stores 1|unlogged|{'json_data': {'json_data': ['Value must be valid JSON.']}} in my db instead of the actual JSON I am sending. So, How do I just simply store the whole JSON in my textfield in whatever format it comes. -
password reset in django
I am trying to send passwword-reset email in django.But for sending that I need to create the google app password.I have generated the app password in google accounts.But I am cannot find where to paste the app password in gmail.Can you guys please help me find out this. -
Why use Django 3?
So we had celery and redis for background tasks / async for django but how does the same thing gets tackled in django 3.0? do we have new inbuilt features for the same in dj 3.0? Thanks in advance. -
HTML Page rel="icon" is not showing up in Django
This is how I've referenced it. {% load static %} <link href="{% static 'Assets/img/globe.png' %}" rel="icon" /> -
Create PDF of Images in Django
In my Django Application I am creating Barcodes of an Object and up until then it works fine, the PNGs are created perfectly but How can I arrange them in a PDF in a 7x2 Grid such that they can be printed? Is there any Library which takes the images as input and create a pdf with these images? Here's the code: class GrnBarcodes(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): pk = self.kwargs['pk'] grn = Grn.objects.filter(pk=pk)[0] grn_prod = grn.items.all() items = [] for i in grn_prod: for j in range(i.item_quantity): items.append("YNT9299"+str(pk)+str(i.item.short_code)+str(j+1)) zpl_img = [] for i in items: barcode = get_barcode(value=i, width=650) a = barcode.save(formats=['PNG'], fnRoot=str(i)) with open(a, 'rb') as image: img = image.read() grf = GRF.from_image(img, 'YNT') grf.optimise_barcodes() # os.remove(a) zpl_img.append(grf.to_zpl()) return Response(zpl_img) The grid that I have to place these images looks like this: -
get () get() returned more than one SubRegion, DJango cities_light
I am using Django Cities_light My files that I want to include CITIES_LIGHT_TRANSLATION_LANGUAGES = ['fr','en'] CITIES_LIGHT_INCLUDE_COUNTRIES = ['CA','US'] CITIES_LIGHT_INCLUDE_CITY_TYPES = ['PPL', 'PPLA', 'PPLA2', 'PPLA3', 'PPLA4', 'PPLC', 'PPLF', 'PPLG', 'PPLL', 'PPLR', 'PPLS', 'STLMT',] When I run the command python manage.py cities_light I just got the error of cities_light.models.MultipleObjectsReturned: get() returned more than one SubRegion -- it returned 35! Any solutions? I want the all cities of Canada and USA -
why i cant take correct id of button jqery in django loop in template
The problem is this. In my loop in the template, I display the + and - buttons for the amount of each product in the cart, while receiving the data and sending it to the server, where I actually process it, and increasing that amount of the product in the cart. template <td class="info col-md-3"> <div class="input-group"> <span class="input-group-btn"> <button id="minus" class="btn btn-danger minus" data-id="{{obj.id}}" type="button">-</button> </span> <input id="calc-button" type="text" class="form-control calc-button" data-id="{{obj.id}}" value="{{obj.quantity}}"> <span class="input-group-btn"> <button id="plus" class="btn btn-success plus" data-id="{{obj.id}}" type="button">+</button> </span> </div> </td> and my view class MainCartPlusValue(View): def post(self, request): print(request.POST) a = dict() a = { 'id': request.POST['id'], 'counts': request.POST['counts'] } obj = Dishes.objects.get(id=request.POST['id']) product = get_object_or_404(Dishes, id=obj.id) """не работает :(""" # if request.POST['counts'] == 3: # cartremove = MainCartRemove # cartremove.get(self=cartremove.self, request=request, key='remove', pk=obj.id) """посюда(""" cart = Cart(request) cart.add(item=product, quantity=request.POST['counts'], update_quantity=True) return JsonResponse(a) if need it my cart def add(self, item, quantity=1, update_quantity=False): product_id = item.id if product_id not in self.cart: self.cart[product_id] = {'quantity': item.counts, 'price': str(item.price), 'name': str(item.name), 'id': item.id } if update_quantity: self.cart[product_id]['quantity'] = quantity print(self.cart[product_id]['quantity']) self.session['cart'] = self.cart self.session.modified = True $(function () { $('.minus').click(function(){ $(".calc-button").val(parseInt($(".calc-button").val())-1), alert( $(".calc-button").val()); const csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); … -
Unique and custom order_id generated by Django Autofield
I am building an e-commerce solution that stores unique and custom order_id's for every single order. The uniqueness is due to the separation of orders for 1 particular customer. The custom part is for the separation of different suppliers. For example: Supplier name = foo order1: order_id = foo-20202907-001 order2: order_id = foo-20202907-002 ... Supplier name = bar order1: order_id = bar-20202907-001 order2: order_id = bar-20202907-002 ... The first part of the order_is is depending on the name of the supplier. Next it will take in a date stamp and lastly it takes auto incremented field for the order amount that day. My current Order model: class Order(models.Model): order_id = models.AutoField(primary_key=True, editable=False) customer_id = models.ForeignKey(User, on_delete=models.CASCADE) The Autofield starts at 1 and increments it every time a new is placed by 1. When a lot of customers are placing different orders at different suppliers the order_id's get really messy. For the sake of the unique id in my payment system i need something like the above order_id's. I've read some articles about on custom unique field but I don't know whats the right approach. Is there a way to do this? -
Python - retrieving slug value from foreingkey class
I'm a newbie in Python and I need some help with my code. Not even sure if my title makes sense. Basically I have my blog and I'm trying to add a sidebar with popular posts. I have created a PostStatistics class to collect the number of visits in each post which can be seen from Django admin. The PostStatistics class has a ForeignKey to the Post class. OK so my problem is in the PostDetail view. I have a QuerySet there called Popular where I retrieve the 5 most popular posts in the last 7 days. There I retrieve the Post_id and Post__Title. I also need to retrive the Post SLUG but I have no idea how I can do that. The slug would be used in the following bit of code: <a href="{% url 'post_detail' pop_article.post_slug %}">{{ pop_article.post__title }}</a> The following is what in my models: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) views = models.PositiveIntegerField(default=0, editable=False) class Meta: ordering = ['-created_on'] db_table = "post" def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return … -
Incorrect application version found on all instances. Expected version "app_version" (deployment 158)
I'm trying to deploy my Django application to Beanstalk but my app health is Degraded for some reason. The log file is also deleted automatically so I cannot read the error. But when I click on "Cause", I get this message: Command failed on all instances. Incorrect application version found on all instances. Expected version "app-fc04-XXXX" (deployment XXX). Application deployment failed at 2020-07-29T07:24:43Z with exit status 1 and error: Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. It's also worth noting that the failure is happening when trying to install from requirements.txt, here's the error: Application deployment failed at 2020-07-29T07:24:43Z with exit status 1 and error: Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. Collecting alphabet-detector==0.0.7 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Using cached https://files.pythonhosted.org/packages/f8/89/c9ab40530fb9142890a79bf39b6f2ee47c311729358794719acd15974e68/alphabet-detector-0.0.7.tar.gz Collecting argcomplete==1.10.0 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Using cached https://files.pythonhosted.org/packages/4d/82/f44c9661e479207348a979b1f6f063625d11dc4ca6256af053719bbb0124/argcomplete-1.10.0-py2.py3-none-any.whl I've tried rebooting the instance, deploying an old working version, and deleting the EC2 instance but none of them work. -
Django activate translations project wide instead of per view?
I have a Django project where I activate the translations based on the Accept-Language header on each and every view as follows, from django.utils import translation translation.activate(request.headers.get('Accept-Language', 'en')) So if I have a ViewSet using Django Rest Framework, I had to do the above for each and every methods as following, class MyViewSet(viewsets.ModelViewSet): def list(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... def retrieve(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... def update(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... def destroy(self, request, *args, **kwargs): translation.activate(request.headers.get('Accept-Language', 'en')) # .... This is just for a viewset, I currently have 10+ viewsets and Translations are needed for every viewset. This make the process even harder to maintain and results in much code duplication. How can I clean up this code to something like activating translations project wide, any options available to do? thank you for any input. -
Many To Many NOT saving in django
my views.py file: form = ClassesForm(request.POST) if form.is_valid(): New_Class = Classes() New_Class.semester = Last_Semester New_Class.year = form.cleaned_data.get('year') if form.cleaned_data.get('year') >= 6 and form.cleaned_data.get('year') <= 8: New_Class.school_mode = 1 else: New_Class.school_mode = 2 New_Class.brunch = form.cleaned_data.get('brunch') New_Class.subject = form.cleaned_data.get('subject') New_Class.teacher.set(Staff.objects.filter(uuid=form.cleaned_data.get('teacher').uuid)) New_Class.save() my models.py file: @reversion.register() class Classes(BaseModel): semester = models.ForeignKey(Semester, on_delete=models.PROTECT,default=get_last_semester, verbose_name=("Semester")) school_mode = models.IntegerField(db_index=True, choices=SCHOOL_MODE, verbose_name=("School Type")) year = models.IntegerField(db_index=True, choices=CLASS_YEARS, verbose_name=("Year")) brunch = models.CharField(max_length=2, verbose_name=("Class Brunch")) subject = models.CharField(max_length=15, choices=CLASS_SUBJECTS, verbose_name=("Subject")) **teacher = models.ManyToManyField(Staff, blank=True, verbose_name=("Class Teachers"))** class Meta: unique_together = ('semester', 'year', 'brunch') ordering = ['semester', 'year', 'brunch', 'subject'] def __unicode__(self): return "%d %s %s %s / %s" % (self.semester, self.year, self.brunch, self.subject) auditlog.register(Classes) @reversion.register() class Staff(BaseModel): photo = models.ImageField(upload_to="Staff/", null=True, blank=True, verbose_name=("Photo")) user = models.OneToOneField(User, on_delete=models.PROTECT, db_index=True, verbose_name=("User")) name = models.CharField(max_length=30, db_index=True, verbose_name=("Name")) surname = models.CharField(max_length=30, db_index=True, verbose_name=("Surname")) id_no = models.CharField(max_length=15, unique=True,verbose_name=("ID Card Number")) birthdate = models.DateField(verbose_name=("Birthdate")) birthplace = models.CharField(max_length=30, verbose_name=("Birthplace")) gender = models.IntegerField(choices=GENDERS, default=None, verbose_name=("Gender")) nationality = models.CharField(choices=NATIONALITIES, max_length=20, verbose_name=("Nationality")) blood_type = models.CharField(choices=BLOOD_TYPES, null=True, blank=True, max_length=10, verbose_name=("Blood Type")) phone_home = models.CharField(max_length=15, null=True, blank=True, verbose_name=("Phone Home")) phone_mobile = models.CharField(max_length=15, null=True, blank=True, verbose_name=("Phone Mobile")) email = models.EmailField(default=None, null=True, blank=True, verbose_name=("Email Address")) address = models.TextField(verbose_name=("Address")) brunch = models.ForeignKey(TeacherBrunch, on_delete=models.PROTECT, verbose_name=("Brunch")) staff_type = models.ManyToManyField(StaffType, verbose_name=("Staff Type")) staff_status = models.IntegerField(choices=STAFF_STATUS, default=1, … -
Does web sockets consume more memory than WSGI app?
I am beginning to explore Django channels (to handle ASGI requests),and created a simple chat app following guide https://channels.readthedocs.io/en/latest/tutorial/part_3.html. If a user started chat with other user and leave chat window as it is, will the server waits / open the websockets until the any of the user closes the window ? If so I suppose that it will need more processor power to support multiple users. -
Save method didn't working for put or patch method in foreign table in djagno rest framework
I'm trying to develop system using django rest frameworks everythings is working fine but i've little but issue. ie save method is not working in foregin table for put and patch method. Suppose I've two table called A and B class A(models.Model): title = models.CharField(..) class B(models.Model): a = models.OneToOneField(A, .....) def save(self, *args, **kwargs): print('test') return super(B, self).save(*args, **kwargs) this is working fine for post method but not for put and patch method. I'm using djago rest frameworks. -
When i delete an object in Django Admin it is still being rendered on the webpage
I've tried to create a simple app that has a list of Categories and each Category has a list of Posts. When I delete a Category object in Django Admin it disappears in Admin but it remains rendered in the template. Here is Admin showing only two Categories However, on the home.html it shows 3.. the base.html serving the Navbar also shows 3 I have cleared cache and hard reload. Here is my code: Views.py from django.shortcuts import render, get_object_or_404 from .models import Post, Category from django.views.generic import ListView, DetailView category_list = Category.objects.all() def privacy(request): return render (request, 'privacy.html', {'category_list':category_list}) def home(request): return render(request,'home.html',{'category_list':category_list}) def categoryDetail(request, slug): category = get_object_or_404(Category, slug=slug) post = Post.objects.filter(category=category) return render(request,'category_detail.html',{'category':category, 'post':post, 'category_list':category_list}) and template, home.html {% if category_list %} <!-- Content Row --> <div class="row"> {% for cat in category_list %} <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title"><a href="{% url 'category_detail' cat.slug %}">{{ cat.name }}</a></h2> <p class="card-text">{{ cat.summary|truncatechars:100 }}</p> </div> <div class="card-footer"> <a href="{% url 'category_detail' cat.slug %}" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> {% endfor %} </div> <!-- /.row --> {% else %} <h3>COMING SOON ...</h3> {% endif %} an similarly in base.html <ul class="navbar-nav ml-auto"> {% for cat … -
Generate same form dynamically pressing a buttom in django
I have modelform called WorkExperienceForm. Currently the form is adding only one information. But work experience can be of multiple times. forms.py: class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] widgets = { 'previous_company_name': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'job_designation': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), 'from_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal3'}, format='%m/%d/%Y'), 'to_date': forms.DateInput(attrs={'class': 'form-control form-control-sm has-feedback-left single_cal', 'id': 'single_cal4'}, format='%m/%d/%Y'), 'job_description': forms.TextInput(attrs={'class': 'form-control form-control-sm'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) I want to add a "Add" button to the frontend. When user presses add button, same form will be generated. This can be done unlimited times. I also want to add a delete button so that user can delete form if he/she creates form mistakenly. How can I do that using javascript??? Any help will be appreciated. -
TypeError: Object of type Decimal is not JSON serializable | Django
I am getting quite unusual error. I got pretty confused because of this. When I iterate over the cart items and try to view them it throws a TypeError Object of type Decimal is not JSON serializable. But if i remove the block from my templates then refresh the page and again add the same block to my templates and refresh the page it works. I have added some screenshots. Please have a look and help me out with this cart.py class Cart(object): def __init__(self, request): """ Initialize the cart """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = { 'quantity': 0, 'price': str(product.price) } if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def __iter__(self): """ Iterate over the items in the cart and get the products from the database """ product_ids = self.cart.keys() # get the product objects and add the o the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in … -
Reading content of docx and save in models.TextField()
I am trying to receive a docx file from user in django, open it, and copy all its content (containing just text and mathematical equations) into textBody of my model. In the model.py I have class myWordFileContent(models.Model): textBody= models.TextField() and in view.py I have def receive_reports(request): if request.method == 'POST': myFile = request.FILES['UserFile'] tempBody= [''] for chunk in myFile.chunks(): tempBody.append(chunk) record = myWrodFileContent.objects.create(textBody= tempBody) return render(request, 'testPage.html') but when I save a docx file content, and go to my model table in admin page I have [",44, 141, 143, 152, 136, 27, 152, 131, 227, 45, 160, 198] Whats wrong? how can I do this to have correct text? -
Mypy linting in VSCode Errors out with "Error constructing plugin instance of NewSemanalDRFPlugin"
Trying to run Mypy linter in VSCode, always getting the same error in the output... ##########Linting Output - mypy########## Error constructing plugin instance of NewSemanalDRFPlugin mypy==0.770 mypy-extensions==0.4.3 django-stubs==1.5.0 djangorestframework-stubs==1.2.0 python3.8.5 Django with DRF -
django - sending email with gmail failure
I'm trying to implement an automatic email sending system with gmail on my django app. This is my view: from .forms import EmailPostForm from django.core.mail import send_mail def post_share(request, post_id): #retrive post by # post = get_object_or_404(Post, id=post_id, status='published') sent=False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form passes validation cd = form.cleaned_data #...send Email post_url = request.build_absolute_uri(post.get_absolute_url()) subject = f"{cd['name']} recomends you read {post.title}" message = f" Read {post.title} at {post_url}\n\n" \ f" {cd['name']}\s comments: {cd['comments']}" send_mail = (subject, message, 'my_gmail_acccount@gmail.com', [cd['to']]) sent=True else: form = EmailPostForm() context = { 'form':form, 'post':post, 'sent': sent } return render(request, 'byExample_django3/post/share.html', context) and my form: from django import forms class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments= forms.CharField(required=False, widget=forms.Textarea) and my template: {% extends "byExample_django3/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p> "{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}. </p> {% else %} <h1>Share "{{ post.title }}" by e-mail</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send e-mail"> </form> {% endif %} {% endblock %} and my url: path('<int:post_id>/share', views.post_share, name='post_share') … -
How can make dynamic id in script with django
I want change js-lightgallery id name to photos name and I change this codes id js-lightgallery make dynamic var $initScope = $('#js-lightgallery'); Gallery.html <div id="js-lightgallery"> {% for photo in post %} {% if photo.ders == a %} {% if photo.img %} <a class="jg-entry entry-visible" href="{{photo.img.url}}" data-sub-html="{{photos.title}}"> <img class="img-responsive" src="{{ photo.img.url }}" alt="{{photo.title}}"> </a> {% endif %} {% endif %} {% endfor %} Script var $initScope = $('#js-lightgallery');