Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add these two elements in my webapp?
I'm doing this django How can I add these two elements in my web app using HTML, CSS, or JavaScript the elements marked in this image below? [1]: https://i.stack.imgur.com/XlIjp.jpg -
Matching array fields containing tags in Django as Trigram only accepts text and not list
Basically I need to match a requested product tag list with other products tag list and prepare the queryset to be reflected as similar products. Models.py title = models.CharField(max_length=300) tags = ArrayField(models.CharField(max_length=100), default=list,null=True,blank=True) Views.py product = Product.objects.all().filter(slug=slug) similar_products = Product.objects.annotate( similarity=TrigramSimilarity('title',product.title),).filter(similarity__gt=0.1).order_by('-similarity') Matching with title field works but as soon as I try to use 'tags' and product.tags to match, it throws error function similarity(character varying[], text[]) does not exist A sample tag list looks like [motor,helmet,bluetooth,speakers] -
how to add a new record to a Many To Many Field
I'm working on a small project using Django / Rest Framework, I have two models ( Contact & List ) I have Many To Many field, in Contact called list. I would like to know how can I add a record to this relation ( Many To Many Field ). from django.db import models # Create your models here. class List(models.Model): name = models.CharField(blank=False, max_length=255) comment = models.CharField(blank=False, max_length=255) private = models.BooleanField(default=False) allowed = models.BooleanField(default=False) def __str__(self): return self.name This is my Contact Model from django.db import models from django.conf import settings from list.models import List # Create your models here. class Contact(models.Model): # field variables language_choices = ( ('french', 'french'), ('english', 'english'), ) """ Relations Between Models """ list = models.ManyToManyField(List) -
Django DRF elastic search dsl, Apply functional boosting based on another field numerical value
I am trying to tune the relevance of my field search result based on another field numerical value (the field is in another model). Looking at the ES documentation it seems that functional boosts is what I need for my usecase. Note that I am using the django-elasticsearch-dsl; package. My use case: I have a search field where users can search for companies based on the company name. I want to return the company names that match the query where sorting (relevance) depends on the company's net asset, where the higher the number, the more relevant (field in another model) Model definition: class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False, null=False) def __str__(self): return self.name class CompanyNetAsset(models.Model): id = models.AutoField(primary_key=True) assets = models.IntegerField company_id = models.ForeignKey('Company', on_delete=models.PROTECT, blank=True, null=True) def __str__(self): return self.name my es document: ... custom_stop_words = token_filter( 'custom_stopwords', type='stop', ignore_case=True, stopwords=['the', 'and'] ) html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["lowercase", "asciifolding", custom_stop_words], char_filter=["html_strip"], ) @INDEX.doc_type class CompanyDocument(Document): id = fields.IntegerField(attr='id') name = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), } ) class Django: model = Company and here is the DocumentViewSet: class CompanyDocumentViewSet(DocumentViewSet): """The Company Document view.""" serializer_class = CompanyDocumentSerializer lookup_field = 'id' document = CompanyDocument filter_backends = [ … -
Multiply three table in DJANGO without raw_sql
I have three models in Django that we could schematize like this : class A(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): c = models.ForeignKey(C, on_delete=models.CASCADE) class C(models.Model): data = models.IntegerField() My aim is to make a query equivalent to : select * from A, B, C where a.b=b.id and b.c=c.id; My question is : Is there a way to make this query without using raw sql ? -
What is the best practice to architect tasks processing using AWS?
I am wondering about how to configure lambda, sns, and sqs for processing background tasks. There are three ways I thought. Option 1. A function called consumer can execute workers by receiving tasks from the queue. Option 2. Send all tasks to SNS. One worker and one SQS receive and work from SNS. Option 3. Directly forward the task to one SQS and one lambda from the APP. The biggest concern is whether to directly invoke Lambda in the app or use task consumer using SQS or SNS. My paintings will help you understand My idea is from Triggering multiple lambda functions from one SQS trigger -
Django, How to display Bid History made on that listing
How can I display only the history of Bids for each specific listing? Right now my page shows all the Bids history no matter for what listing on the website Models.py class AuctionListing(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_bid = models.IntegerField(null=True) image = models.CharField(max_length=1000, blank=True) category = models.CharField(max_length=100) seller = models.CharField(max_length=100, default="Default_Value") def __str__(self): return f"{self.title} listing | {self.seller}" class Bid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_bids") listing = models.ForeignKey(AuctionListing, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) bid_time = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} put a bid in for {self.price}" Views.py def view_bids(request, product_id): return render(request, "auctions/view_bids.html") view_bids.html {% extends "auctions/layout.html" %} {% block title %} Item Bid History {% endblock %} {% block body %} <div class="col-md-5"> <div class="thumbnail text-center"> <h4>Bid History</h4> {% for user in user.user_bids.all %} <strong> {{user.user}} - {{user.price}}$ - {{user.bid_time}} </strong> <br> {% endfor %} </div> </div> {% endblock %} Thanks for any help :) -
Django REST Implement Custom Authentication for specific API views
My requirement is quite different, i have already implemented Django Rest framework and rest_auth for my my api and the views authenticating with bearer token which generated by django rest framework and rest_auth I have an API for public user, who will subscribe to my application, then will generate API token by their own and it will be used only for a specific API views. For example, aws, google, facebook, has its own API and their end user can delete/generate new token orsecret key by their own to authenticate their particular API. I have the same requirements, I want, user should able generate/delete/disable API key from the web gui by their own. Can anyone please tell me how can i make it possible with django rest framework? -
Can't import python script into another script
I'm trying to import a python script twitter.py into my views.py, whilst working in Django. This file exists in the same directory as my views.py file. Whenever I tried to run python manage.py runserver command from the terminal to open my web page locally, I receive: *ModuleNotFoundError: No module named 'twitter'* Things I've tried: putting twitter.py in a new folder in the directory, and adding __ init __.py (no spaces) to that directory so python reads it as a module The directory both files exist are already in my PYTHONPATH I didn't post any code because this is a fairly trivial issue that I never thought I'd have trouble solving. Thanks -
djqgrid: No module named 'json_helpers'
I'm trying to use JQGrid in a Django web application I've done a pip install of django-jquery==3.1.0 djqgrid==0.2.4 But when I "runserver" I get the following error message:- File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\aabel\PycharmProjects\djangoWithJQGrid\djangoWithJQGrid\urls.py", line 19, in <module> from Accounts.views import account_list_view File "C:\Users\aabel\PycharmProjects\djangoWithJQGrid\Accounts\views.py", line 11, in <module> from djqgrid.columns import TextColumn File "C:\Users\aabel\PycharmProjects\djangoWithJQGrid\venv\lib\site-packages\djqgrid\columns.py", line 4, in <module> from json_helpers import function ModuleNotFoundError: No module named 'json_helpers' In my urls.py I have:- urlpatterns = [ path('', account_list_view, name='home'), ... ] In Accounts.views.py I have:- from djqgrid.columns import TextColumn from djqgrid.grid import Grid class AccountGrid(Grid): model = Account account_id = TextColumn(title='account_id', model_path='account_id') name = TextColumn(title='name', model_path='name', align='right') def account_list_view(request): grid = AccountGrid() return render(request, 'account_list.html', { grid: grid }) I know that 'json_helpers' is part of the djqgrid package (which I installed with pip). So am I missing a reference to it somewhere? Thanks. -
Caching queryset in django rest framwork?
I have a large queryset and I have a Paginator for the generics.ListAPIView. I want to cache that queryset with its all page, but i think it doesn't work that way. I've been trying to figure out how to cache the queryset with the Paginator but I don't seem to find a way to make it work with Django Rest. this is my pagination class: class StandardPagesPagination(PageNumberPagination): page_size = 35 def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'total_pages': self.page.paginator.num_pages, 'results': data }) and this is my view: class OyunlarList(generics.ListAPIView): # queryset = Oyunlar.objects.all() filter_backends = [DjangoFilterBackend,filters.SearchFilter,filters.OrderingFilter] search_fields=['title'] filterset_fields=['categories__name','platform','categories__category_id','game_id'] ordering_fields = ['title', 'release_date','click_count','popularite'] pagination_class = StandardPagesPagination serializer_class = OyunlarSerializer def get_queryset(self): queryset=Oyunlar.objects.all().order_by('click_count').prefetch_related('categories') #queryset=Oyunlar.objects.raw("select 'game_id' AS id,'title','base_price','en_ucuz' from oyunlar ") return queryset @method_decorator(cache_page(60 * 3)) def dispatch(self, *args, **kwargs): return super(OyunlarList, self).dispatch(*args, **kwargs) I want to give user a more smooth experience. -
How to only require min in forms.dateinput if the date is changed
I have a form with a dateinput which I would like to only have change the due date in case the user decides to input a new date. here's my form: class TaskCreateForm(forms.ModelForm): class Meta: model = Task fields =["task_name", "assigned_to", "status", "deadline", ] widgets = { 'deadline': forms.DateInput(attrs={'min': timezone.localdate(), 'type':'date'}), } Here's my view: class TaskUpdate(UpdateView): model = Task template_name = "todo_list/task_update.html" form_class = TaskCreateForm success_url = reverse_lazy('tasks') and here's my template: <h1>Update Task</h1> <a href="{% url 'tasks' %}">go back</a> <form method="POST" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> Any help is much appreciated. Thank you in advance -
How do I append to python subdict array?
I want to print something like the following but I don't know how to add/append to the python dict array. dict = [{ "court_name": "court 1", "bookings": [{ "start_time": "8pm" }] }, { "court_name": "court 2", "bookings": [{ "start_time": "8pm" }, { "start_time": "9pm" }] }] I have a bunch of booking slots and I want to render them like above using a for loop. How do I append/add objects to the dict as what I am trying doesn't work? slots = {} prev_court = -1 for booking in instances_sorted: this_court = booking['location_id'] if this_court == prev_court: # court is the same slots[len(slots)-1]["slots"].append({ "start_time": booking.start_time, }) else: # new court slots.append{ "court_name": booking.location__court_name, "slots" : [{ "start_time": booking.start_time, }] } prev_court = this_court I feel like this should be pretty simple but couldn't find anything great when I searched for similar answers. Thanks for the help! -
how to solve this simple Django CRUD programming problem?
Hi, i am tryting to solve this problem but i don't seem to get anywhere, when i create objects to the database i'm used to have a form, also i am not sure how to return a jsonreponse in django, can you help me? Here is the problem: You are writing a simple CRUD application in Django (2.0.5) for managing a zoo. It has to allow particular animals to be added and removed, and to track the time when they were last fed. Animals must have names that are unique across all species. Unfortunately, the creator of this model didn't provide unique constraints regarding the name at the database level, so you need to take this into account in the views. Models are implemented in the following way: from django.utils import timezone from django.db import models class Species(models.Model): name = models.CharField(max_length=30, primary_key=True) class Animal(models.Model): name = models.CharField(max_length=30) species = models.ForeignKey(Species, on_delete=models.CASCADE) last_feed_time = models.DateTimeField(default=timezone.now) Requirements Implement a GET request handler in the class-based view AnimalPopulationView that returns the total number of animals in the zoo. It should return an HTTPResponse with a number. Implement a GET request handler in the class-based view AnimalView that returns data about an animal in … -
Schema created but no data present after switching from sqlitedb to PostgreSQL while using django frame work
Working on a Django web-app for 2 months now. I have accumulated lot of data on the database, (sqlitedb by default). And Now I plan to switch to PostgreSQL. I have tried to follow the standard proceddure. python manage.py dumpdata --indent=4 > datadump.json # now changed the DATABASES=[...] in the settings.py python manage.py migrate --run-syncdb python manage.py loaddata datadump.json In the last step the output was Installed 156 objects from 1 fixture, which is expected I guess. However, when I open connect to db using the using pgadmin4 and run a query select * from table_name. Additionally, when I open the web app now there are no data available(no user, no post data and so on). Note : The schema has been created in the database indeed, but there is no data there. What is the way to get data there as well? Is loaddata not enough ? -
Appsheet saving to S3
We have a single database we are using with PostgreSQL and when appsheets saves the data it only provides I believe what is called the file path from the work load. However its saving from the default settings of appsheet/data/{appname}/{folder}/. That works fine for appsheets but us developers using boto3 with django can't find the images. Working with the Appsheets member and doing research we found a field called default app folder and every time we try make that field empty it results back to the main setting path. Now we can't change the main setting path for the profile because they have tons of other apps in appsheets that use that path. However for this one app we need to make it empty so it will save correctly into s3 and have the right path in postgreSQL. I hope this explains the issue and be happy to answer any additional questions. -
I don't know why my views on django is not displaying on the browser
I don't know why my views on django is not displaying on the browser, I'm new to django and I'm just trying to create a very basic new user view but for some weird reason is not working and I can't understand what is the problem. Please help me to at the code: project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('logapp.urls')), path('admin/', admin.site.urls), ] app url.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home") ] views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("<h1>Hello world</h1>") setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'logapp', ] Those are the only things I did after creating virtualenv. The project is running and displaying only the default django rocket. -
Attempting to set related model fields via parent function call(s)
I am writing a Compact Disk Library editing routine. The application allows you to enter a CD Artist Name, and CD Title and the total time of the CD. User can then enter track information. While entering track information I want the application to display Current run time including this track, and time remaining based on length of the CD. The models and functions are below class Cd(models.Model): artist_name = models.CharField(max_length=155) cd_title = models.CharField(max_length=155) cd_total_time = models.TimeField(default="00:00:00") cd_total_time_delta = models.DurationField(default=timedelta) cd_run_time = models.TimeField(default="00:00:00",blank=True) cd_run_time_delta = models.DurationField(default=timedelta) cd_remaining_time = models.TimeField(default="00:00:00",blank=True) cd_remaining_time_delta = models.DurationField(default=timedelta) def convert_to_delta(self,time_in): hold_time = time_in.strftime("%H:%M:%S") t = datetime.strptime(hold_time,"%H:%M:%S") return(timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)) def calculate_time(self): cd_total_time_delta = self.convert_to_delta(self.cd_total_time) cd_total_run_time_delta = timedelta(minutes=0) for track in self.cd_tracks.all(): cd_total_run_time_delta += track.trk_length_time_delta track.trk_run_time_delta += cd_total_run_time_delta track.trk_run_time = f"{track.trk_run_time_delta}" track.trk_remaining_time_delta = cd_total_time_delta - cd_total_run_time_delta track.trk_remaining_time = f"{track.trk_remaining_time_delta}" self.cd_run_time_delta = cd_total_run_time_delta self.cd_run_time = f"{self.cd_run_time_delta}" self.cd_remaining_time_delta = self.cd_total_time_delta - cd_total_run_time_delta self.cd_remaining_time = f"{abs(self.cd_remaining_time_delta)}" def save(self, *args, **kwargs): self.calculate_time() super().save(*args,**kwargs) def __str__(self): return f"{self.artist_name} : {self.cd_title}" class Track(models.Model): cd_id = models.ForeignKey(Cd, on_delete=models.CASCADE, related_name='cd_tracks', ) track_title = models.CharField(max_length=50) track_number = models.IntegerField() trk_length_time = models.TimeField(null=True,default=None, blank=True) trk_length_time_delta = models.DurationField(default=timedelta) trk_run_time = models.TimeField(default="00:00:00",blank=True) trk_run_time_delta = models.DurationField(default=timedelta) trk_remaining_time = models.TimeField(default="00:00:00",blank=True) trk_remaining_time_delta = models.DurationField(default=timedelta) def calculate_track_delta(self): self.trk_length_time_delta = self.cd_id.convert_to_delta(self.trk_length_time) def save(self, *args, **kwargs): … -
Django ListView how to zip context data with another context
I'm trying to add some context to my ListView context and access them in one for loop with zip like this class WeatherListView(ListView): """ List view of Weather data """ template_name = "frontend/weather_list.html" model = Weather def get_context_data(self, **kwargs): weather_query = Weather.objects.all() temp_list = list(weather_query.values_list('temperature', flat=True)) humidity_list = list(weather_query.values_list('humidity', flat=True)) temp_list_compared = compare_item_to_previous(temp_list) humidity_list_compared = compare_item_to_previous(humidity_list) data = super().get_context_data(**kwargs) context = { "object_list": zip(data, temp_list_compared, humidity_list_compared) } return context Then I want to get my data in the template for loop {% for i in object_list %} {{ i.0.some_field_in_original_context }} {{ i.1 }} {{ i.2 }} {% endfor %} But what I end up having for my original context {{ i.0 }} is this paginator page_obj is_paginated How can I still access my original ListView data after putting it in a zip. -
Downloaded pdf file trimmed from django
I am trying to create a site in django (version 1.11) that will download a file resides on the host. I have used the following code: views.py: def download_file(request,fl_path): data = subject.objects.all() sub = { "subject_id": data } fl_path = data.values('submissions')[0]['submissions'] filename = fl_path.split('/')[1] fl = open(fl_path, 'r') response = HttpResponse(fl, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=%s" % filename return response models.py: class subject(models.Model): nameSubject = models.CharField(max_length=200, primary_key=True) songs = models.CharField(max_length=2000) selfTasks = models.CharField(max_length=2000) submissions = models.FileField(upload_to='submissionsTasks') def __str__(self): return self.nameSubject The file is downloading successfully, with file name and all. The point is that the file is trimmed at 2KB of size. The downloaded file contains an identical copy of the first 2KB of the original file. Do we have any setting that should allow >2KB file download? Any other solutions / ideas? Thanks in advanced, Michal -
In Django no other function getting called except one rest showing error 403
This is our code for url from django.conf.urls import url,include from django.urls import path,re_path from . import views app_name = 'challengeide' urlpatterns = [ url('challengeide', views.qtn,name='test'), url('challenge/', views.challengeide, name='challengeide'), url('challenge/', views.dataentry, name='dataentry'), #url('challengeide', views.dataentry,name='dataentry'), path('challenge/challengeide/', views.send_challenge_request, name='send_challenge_request'), ] this is code for views from django.shortcuts import render from django.http import JsonResponse, HttpResponseForbidden import requests from challengeide.models import Challenge_Detail from challengeide.models import ChallengeDemo import json from django.utils.datastructures import MultiValueDictKeyError from users.models import Profile from django.shortcuts import redirect, get_object_or_404 from django.http.response import HttpResponseRedirect from django.contrib.auth import get_user_model def qtn(request): try: #print("If loop") data = request.POST['opponent'] data1 = request.POST['qts'] opponent_row = Profile.objects.get(slug = data) global to_id to_id = opponent_row.user_id print(data,data1) global a a = int(data1) question_desc = Challenge_Detail.objects.get(id = a) #print(a) #dataentry(request) return render(request,"challengeide.html",{'ChallengeDetails':question_desc}) except MultiValueDictKeyError : #print("in else") question_desc = Challenge_Detail.objects.get(id = a) e1 = question_desc.expout e2 = question_desc.expout2 e3 = question_desc.expout3 e4 = question_desc.expout4 e5 = question_desc.expout5 i1 = question_desc.expin i2 = question_desc.expin2 i3 = question_desc.expin3 i4 = question_desc.expin4 i5 = question_desc.expin5 for i in range(1,6): if (i==1): if request.is_ajax(): source = request.POST['source'] lang = request.POST['lang'] data = { 'client_secret': 'a4b7d06f4c25bf97ed19ebe68eadaaff39faf493' , 'async': 0, 'source': source, 'lang': lang, 'time_limit': 5, 'memory_limit': 262144, } x = str(i1) i1 = x.replace("qwe","\n") data['input'] = … -
Wagtail admin: How to customize layout of select/checkbox options?
I have a wagtail admin form where I want to customize the layout of a series of checkbox options used to populate a ManyToMany Field. The model I'm editing is called "Product"; the field is "displays_on_pages", and that links to a separate "GenericPage" model. The problem is, I have so many of these pages available as options that it makes displaying them as a regular list of checkboxes a bit unwieldy. I'd like to display them nested instead, so that I can indent the subpages under their parent pages. Something like this: □ Parent Page 1 □ Subpage 1.1 □ Subpage 1.1.1 □ Subpage 1.2 □ Parent Page 2 □ Subpage 2.1 (etc.) I've figured out how to create a custom form widget by subclassing forms.widgets.CheckboxSelectMultiple, how to pass in my own query logic so that the pages available as choices for the checkbox widget appear sorted as a tree, and how to set up a template for the output. The problem is that the choices I'm passing into the template don't appear to be actual "Page" objects. As I loop through the queryset, I can get the value (id) and label (title) for each option, but I can't seem … -
how to use validate_password function with user on user register in django rest framework?
I want to use validate_password() function to check if user data like(name, username, last_name) is similar to password or not. this is my code in serializers.py class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())]) password1 = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField( write_only=True, required=True, validators=[validate_password]) class Meta: model = User fields = ( 'username', 'password1', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': False}, 'last_name': {'required': False}, } def validate(self, attrs): if attrs['password1'] != attrs['password2']: raise serializers.ValidationError( {'password1': "password field dont match !"}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], ) if 'first_name' not in validated_data: user.first_name = "" else: user.first_name = validated_data['first_name'] if 'last_name' not in validated_data: user.last_name = "" else: user.last_name = validated_data['last_name'] user.is_active = False user.set_password(validated_data['password1']) profile = Profile.objects.create(user=user) profile.save() user.is_active = True user.save() return user I need to validate like: validate_password(password, user=user) but how can I have access to user variable contain user object in create() ? -
Django won't recognize {% static %} tag inside an href or image src in html file
The {% load static %} tag at the top of my html file seems to work When I try to link my css file from static folder using this code : {% load static %} <link href="{% static 'static/style.css' %}" rel="stylesheet"> it tries to create a file called {% static 'static/style.css' %}, which means the static keyword isn't being recognized. Any help in figuring out why would be highly appreciated Here's my relevant settings.py to link static files INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/Google_Solutions/static/', ] My static and templates are in the main directory and here's my home.html file head where i'm trying to include files {% extends 'layout.html' %} {% load static %} {% block head %} <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title> Homepage </title> <!-- Vendor CSS Files --> <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"> <link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet"> <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet"> <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet"> <!-- Template Main CSS File --> {% load static %} <link href="{% static 'css/style.css' %}" rel="stylesheet"> {% endblock %} here's my layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="icon" type="image/png" sizes="16x16" href="{% static '/favicon-16x16.png'%}"> <link rel="manifest" href='{%static … -
how variable passed in context convert in html if use {{}}
variable passed using render when we write variable inside in html file using {{}} does it convert from queryset(complex object) to html St=Student.object.filter(id=1) return render(request,'stur.html',{'st':st}) or when passed python object St=[1,2,3] return render(request,'stur.html',{'st':st})