Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can upload to S3 but not Get from S3
I have configured django to use s3 to hold media files. I can from the application upload files and they are stored on the s3, however if i try to view these media files i get this error. <Error> <Code>SignatureDoesNotMatch</Code> <Message> The request signature we calculated does not match the signature you provided. Check your key and signing method. </Message> I know GET requests are enabled as I can use Postman to get the images using the same credentials. So I'm not entirely sure whats wrong. STATIC_ROOT = os.path.join(BASE_DIR, '/staticfiles/') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, '/image_library/') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = 'PLACEHOLDER' AWS_SECRET_ACCESS_KEY = 'PLACEHOLDER' AWS_STORAGE_BUCKET_NAME = 'childcaredevapp' AWS_DEFAULT_ACL = None AWS_S3_FILE_OVERWRITE = False AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_REGION_NAME = 'eu-central-1' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
How to allow anonymous post requests, but deny unauthorized get requests in django?
In C# you can easily attach [AllowAnonymous] to a request so that that specific method can be used. In django however I am a bit confused with Views, Serializers, ... Am I correct that a ViewSet allows you to see what a certain Serializer class contains? If so I would want that to be hidden ofcourse in the case of users. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) This is how I implemented it and it works just fine. So when I go to http://127.0.0.1:8000/api/users/ I get an error that I am not authenticated. Now the problem is with registering a new user. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def create(self, validated_data, AllowAny): user = User.objects.create_user(**validated_data) return user When I hit http://127.0.0.1:8000/api/users/ with a post request in my Angular app with newly registered userData, I obviously get an authentication error. How can I resolve that I or anyone with not enough rights, is not allowed to SEE the data of users, but however everyone is able to create (post) a new user? -
How to set an initial model field to inherent from previous views
I'm using Django to create an application that acts as a project management system. I have it set to where a user can create a project and then they can upload files that are grouped under that project. I use two models to achieve this, Projects and Drawings with Drawing using a foreign key field from Projects to create the relationship. My issue is that when users are viewing a specific project I would like the Drawing form to inherit the name of the project they were just looking at so that we don't get improperly uploaded files. I think I might be able to achieve this from the init method but not entirely sure how to grab the previous pk coming from the last view. path('project_drawings/<int:pk>/', views.ProjectDrawings, name='project_drawings'), path('project_drawingscreate/', views.ProjectDrawingsCreate.as_view(), name='project_drawingscreate'), class DrawingsForm(forms.ModelForm): def __init__(self, project ): class Meta(): model = Drawings fields = ('project', 'title', 'drawings', ) widgets = { 'project':forms.Select(attrs={'class':'form-control'}), 'title':forms.TextInput(attrs={'class':'form-control'}), } class ProjectDrawingsCreate(LoginRequiredMixin,generic.CreateView): form_class = DrawingsForm model = Drawings template_name = 'projects/project_drawingscreate.html' def form_valid(self, form, **kwargs): drawings = form.save(commit=False) drawings.user = self.request.user drawings.save() form.save_m2m() return redirect('projects:index') -
django how to set relation to some fields
i want to set relation in that case class SaleType(models.Model): price = models.CharField(max_length=50) contract = models.CharField(max_length=50) class SaleType2(models.Model): totalContract = models.CharField(max_length=50) requierd = models.CharField(max_length=50) def __str__(self): return str(self.price) class ForSale(models.Model): method = models.ForeignKey(Method, on_delete=models.CASCADE) def __str__(self): return str(self.method) that every method in ForSale have some fields from SaleType -
How to pass multiple authentication_classes in django rest framework?
I want to create an api which can be accessed using client_id and client_secret as well as access token. To access api using client_id and client_secret I have a custom authentication class like this:- class ClientAuthentication(authentication.BaseAuthentication): @staticmethod def get_client_credentials(request): try: client_id = request.headers.get('CLIENTID') client_secret = request.headers.get('CLIENTSECRET') except: raise AuthenticationFailed return { 'client_id': client_id, 'client_secret': client_secret } def authenticate(self, request): credentials = self.get_client_credentials(request) client_instance = Application.objects.filter( client_id=credentials['client_id'], client_secret=credentials['client_secret'], ).first() if not client_instance: raise AuthenticationFailed return client_instance, None def get_user_application(self, request): credentials = self.get_client_credentials(request) application_instance = Application.objects.filter( client_id=credentials['client_id'], client_secret=credentials['client_secret'], ).first() if not application_instance: raise AuthenticationFailed return application_instance, None And the other authentication class i want to use is default OAuth2Authentication I tried passing the authentication_classes for viewset as: authentication_classes = [ClientAuthentication | OAuth2Authentication] But it gives me an error. How can I achieve this? -
SESSION_EXPIRE_AT_BROWSER_CLOSE where we need to write in our project in django?
In django for expire a session after closing a browser where we need to type SESSION_EXPIRE_AT_BROWSER_CLOSE this in which file?? -
django rest_framework with React
I am trying to build an application with django as backend using REST API and front end with React. I have a model named User which contains attributes like firstname, lastname, email,password,description etc, now from front end I want to create a new user and save it to my Database, I can do this using axios and calling out put method, but before saving it to my Database I want to the profile to be verified by admin panel, like whenever user tries to signUp a new_request profile is triggered and the profile goes to admins, if they accept the profile the user is successfully added to the database, I am not getting how to do this stuff! -
How to display the old of the post in django using python?
Help me guys i am new to django and here too,, how can i display the old of the post in django so that the post time will be shown as posted 0 minute ago,, 3 weeks ago and so on to years?? -
Error during template rendering (NoReverseMatch) in Django 3.0.3
Error : Reverse for 'lesson-detail' with keyword arguments '{'course_slug': 'django-101', 'lesson-slug': 'first'}' not found. 1 pattern(s) tried: ['(?P < course_slug>[^/]+)/(?P< lesson_slug>[^/]+)$'] urls.py from django.urls import path from .views import CourseListView, CourseDetailView, LessonDetailView app_name = 'courses' urlpatterns = [ path('', CourseListView.as_view(), name='list'), path('<slug>', CourseDetailView.as_view(), name='detail'), path('<course_slug>/<lesson_slug>', LessonDetailView.as_view(), name='lesson-detail') ] course_detail.html <!DOCTYPE html> <html> <head> <title>Detail view</title> </head> <body> {{ object.title }} {% for lesson in object.lessons %} <a href="{{ lesson.get_absolute_url }}">{{ lesson.title }}</a> {% endfor %} </body> </html> -
im not able to makemigrations to my already built model after extending user model to it in django
im just stuck with error while making migrations to my django project. in my project which is already 50% dveloped i use owner model to represent owner of shop and then i used user model for login and for registration purpose. so i tried to use user model in my owner model so i could utilise both model effectively with additional fields. i tried to extend user model in owner model using onetoone field. after doing that i was not able to do migrations so i deleted all migrations files but after that it was start giving this error while doing migrations:- py manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 87, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\Mayur\PycharmProjects\StartUp\venv\lib\site-packages\django\db\migrations\graph.py", … -
Django-Insert Drop Down Value to postgresql
I'm very new to Django and I would like to Insert a drop down box value to database: Created two django-apps named 'Projects' and 'Clients'.After add the relevant client data ,I am trying to add the corresponding project through drop down ,the values comes from project app's corresponding table. But something went wrong , clients model Create your models here. class clients(models.Model): cname=models.CharField(max_length=20) cadd=models.TextField(max_length=50) cmob=models.BigIntegerField() cemail=models.EmailField(max_length=100) cproject=models.CharField(max_length=50,default=None) class Meta: db_table="client" project model class projects(models.Model): pname=models.CharField(max_length=100) pcode=models.CharField(max_length=100) loc=models.CharField(max_length=50) class Meta: db_table="projects" corresponding Views for add drop down value clients app def add(request): # show projects details from DB if projects.objects.count()>0: data=projects.objects.all() return render(request,'add.html',{'data':data}) else: return render(request,'add.html') def addpro(request): if request.method=="POST": temp.cproject=request.POST['sel'] temp.save() return redirect(addpro) else: return render(request,'add.html') html for dropdown list and selection <div class="container"> <form method="POST"> {% csrf_token %} <select name="sel"> <option selected disabled="true"> -- Select -- </option> {% for var in data %} <option >{{var.pname}}</option> {% endfor %} </select> <a class="btn btn-info" type="submit" href="{% url 'addpro'%}"><i class="fas fa-list-alt"></i>Add</a> </form> </div> -
HTTP Error 401: Unauthorized SendGrid django
I'm trying to do mail subscription on my django website I was following instructions online on how to achieve this. I went through it carefully but whenever I enter and email is say HTTP Error 401: Unauthorized. I went ovewr the instructions and couldn't find were i went wrong. Settings code FROM_EMAIL = 'newsletter@example.com' # replace with your address SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') Models code: class Subscriber(models.Model): email = models.EmailField(unique=True) conf_num = models.CharField(max_length=15) confirmed = models.BooleanField(default=False) def __str__(self): return self.email + " (" + ("not " if not self.confirmed else "") + "confirmed)" class Newsletter(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subject = models.CharField(max_length=150) contents = models.FileField(upload_to='uploaded_newsletters/') def __str__(self): return self.subject + " " + self.created_at.strftime("%B %d, %Y") def send(self, request): contents = self.contents.read().decode('utf-8') subscribers = Subscriber.objects.filter(confirmed=True) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) for sub in subscribers: message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject=self.subject, html_content=contents + ( '<br><a href="{}/delete/?email={}&conf_num={}">Unsubscribe</a>.').format( request.build_absolute_uri('/delete/'), sub.email, sub.conf_num)) sg.send(message) Views.py def random_digits(): return "%0.12d" % random.randint(0, 999999999999) @csrf_exempt def subscribe(request): if request.method == 'POST': sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject='Newsletter Confirmation', html_content='Thank you for signing up for my email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'), … -
Django adding placeholder text for PasswordChangeView?
A user can change their password on my change password page: <form class="password-change-form" method="POST"> {% csrf_token %} <div> {{ form }} </div> <input class="submit-button" type="submit" value="Change password"> </form> My urls.py: path( 'accounts/password_change/', auth_views.PasswordChangeView.as_view(template_name='account/password_change_form.html'), name='password_change' ), The problem PasswordChangeView uses PasswordChangeForm by default. I would like to add placeholder text to this form i.e. Old password placeholder text: 'Enter your old password'. How can I best do this? -
Facing xome issue while running a docker build contains a django project code
I am working on a project, Generating a pdf file after rendering a HTML template with dynamic data using pdfkit which requires wkhtmltopdf that needs to b e installed on root or any directory, i installed it on root and everything is working fine locally but when i am making a docker build to push on a server then its returning an error because of wkhtmltopdf package not found, can anyone guide to solve the error. -
how to use FilterSet in django with DateTimeFromToRangeFilter
I'm trying to filter a Model using Filterset (django-filter) and render from/to select form field in my Template. Unfortunately I cannot figure out how to get it working. While my "code" and "power_category" fields render fine, only a text field gets displayed when trying to render the "reported" field, unless I set type="date", then the datepicker pops up when clicking the date field, however only one shows up (need two, "to" and "from" to select the range). I'm using django 3.0.5, django_filters and widget_tweaks are included in settings and I see no errors. Thank you for your time... Filters.py import django_filters from django_filters import DateRangeFilter, DateFilter from django_filters import DateTimeFromToRangeFilter from django_filters.widgets import RangeWidget from reports.models import Report from django import forms class PostFilter(django_filters.FilterSet): reported = django_filters.DateTimeFromToRangeFilter( widget=django_filters.widgets.RangeWidget( attrs={'class': 'datepicker'} ) ) class Meta: model = Report first_name = django_filters.CharFilter(lookup_expr='icontains') fields = ['reported', 'fixed', 'code', 'power_category'] ] Template {% load widget_tweaks %} <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.code.label_tag }}<br /> {% render_field filter.form.code class="form-control" %} </div><br /><br /> <div class="form-group col-sm-4 col-md-3"> {{ filter.form.power_category.label_tag }}<br /> {% render_field filter.form.power_category class="form-control" %} </div> <div>Date_Time {{ filter.form.reported.label_tag }} {% render_field filter.form.reported %} </div> … -
ModuleNotFoundError while importing a class from different app
In my django project LibraryManagement I have two apps 'book' and 'authors'. I am trying to establish relationship between two apps using foreign key. While I try to import class Authors in the book I got error ModuleNotFound:No module named 'LibraryManagement.authors' Below is my project structure LMS -LibraryManagement -authors -book -LibraryManagement -venv Code of models.py from authors app from django.db import models class Authors(models.Model): author_name = models.CharField(max_length=100) description = models.TextField(max_length=300) Code of models.py from book app from django.db import models from LibraryManagement.authors.models import Authors class Book(models.Model): book_name = models.CharField(max_length=100) author = models.ForeignKey(Authors) remarks = models.TextField(max_length=300) -
Default HyperlinkedModelSerializer not finding the endpoints
I am trying to simply change my ModelSerializer to HyperlinkedModelSerializer to include the url to each of the objects listed in the ListView of the default Browsable API. According to the docs, since I am using default 'pk' for the lookup, I just change the class I inherit the serializer from: # class SeasonSerializer(serializers.ModelSerializer): class SeasonSerializer(serializers.HyperlinkedModelSerializer): # url = serializers.HyperlinkedIdentityField( # view_name='season', lookup_field='pk') ---> Not needed according to docs but have also tried with this class Meta: model = Season fields = ('id', 'url', 'years', 'active') And add the context when instantiating it in the view: class SeasonListView(APIView): def get(self, request, *args, **kwargs): queryset = Season.objects.all().order_by('years') serializer = SeasonSerializer( queryset, many=True, context={'request': request}) print('INFO: ', serializer) permission_classes = [ ] authentication_classes = [ ] return Response({"Seasons": serializer.data}) class SeasonDetailView(APIView): def get(self, request, *args, **kwargs): pk = kwargs['pk'] season = get_object_or_404(Season, pk=pk) serializer = SeasonSerializer(season, context={'request': request}) # print('Data: ', serializer.data) --> this breaks return Response(serializer.data) And my endpoints are the same as when using ModelSerializer: urlpatterns = [ path(r'seasons/', SeasonListView.as_view(), name='season-list'), path(r'seasons/<int:pk>/', SeasonDetailView.as_view(), name='season-detail'), ] The error is the following: For http://localhost:8000/api/seasons/1/ Exception Type: ImproperlyConfigured Exception Value: Could not resolve URL for hyperlinked relationship using view name "season-detail". You may … -
How to ensure all custom values from settings.py are avaibalable in Django project?
I defined a few custom values in my Django project "settings.py" file. I need to load those values into my views ans other project files, but not all values defined in settings.py seem to be available. settings.py # My custom settings API_URL = 'http://10.0.0.1' EMAIL_DEFAULT_RECIPIENT = 'foo@bar.tld' I load the whole settings.py file content using the following in my view: views.py my_view(request,foo_id): from django.conf import settings as project_settings # First log output logger.debug('API_URL: ' + project_settings.API_URL) # Second log output logger.debug('EMAIL_DEFAULT_RECIPIENT: ' + project_settings.EMAIL_DEFAULT_RECIPIENT) The first log output (API_URL value) is correct: [2020-00-00 00:00:00 +0000] [16381] [DEBUG] (my_app.views) API_URL : http://10.0.0.1 Strangely the second log output (EMAIL_DEFAULT_RECIPIENT value) throws an exception: AttributeError: 'Settings' object has no attribute 'EMAIL_DEFAULT_RECIPIENT' Django project layout my_project ├── my_app │ ├── migrations │ ├── __pycache__ │ └── templates ├── my_project │ ├── __pycache__ │ ├── static │ └── templates ├── __pycache__ └── venv ├── bin ├── include ├── lib └── lib64 -> lib My Django project is served through NGINX/Gunicorn started by a systemd service unit within a venv. It worth mentionning that I restarted this service after changing settings.py content. I also cleared __pycache__ project directory content manually but this has no effect on … -
Get group name of the user in Django keycloak
I am using keycloak and django for authentication of users via django-keycloak package. I want to get the group name of a user belonging to in keycloak in django. Also I am new to keycloak authorization service -
Axios post request with nested object
I need help with axios post with multiple student objects in one single class. Class form has various fields with an option to add dynamically multiple students. Add only student names for the objects but be able to edit the student details to give full details.Backend is Django. { "students": [ { "stud_fname": "First Name", "inter_lname": "Last Name", "class_section": "class", }, { "stud_fname": "First dsfdsfName", "inter_lname": "Last sdfName", "class_section": "cladsfdfss", } ], "ClassName": "eqwe", "TeacherName": "eqw", "SchoolNAme": "eqw", } -
Setting up router with APIView and viewset in Django Rest Framework
It's my first question on Stackoverflow ! I'm new to Django and following some tutorials. I'm trying to understand if there is a way to set up the routing of an API from different view classes like APIView and viewsets.ModelViewSet (please tell me if I do not use the good wording) In views I have : from rest_framework import viewsets from post.models import UniquePost from .serializers import UniquePostSerializers from rest_framework.views import APIView class UniquePostViewSet(viewsets.ModelViewSet): serializer_class = UniquePostSerializers queryset = UniquePost.objects.all() class FileUploadView(APIView): some code here but no queryset nor serialized data...and no model In urls I have : from post.api.views import UniquePostViewSet from django.urls import path, include from rest_framework.routers import DefaultRouter from post.api.views import FileUploadView router = DefaultRouter() router.register('UniquePost', UniquePostViewSet, base_name='uniquepostitem') router.register('demo', FileUploadView, base_name='file-upload-demo') urlpatterns = router.urls But it seems that I can register FileUploadView this way. Because I don't have a queryset to render. I have : AttributeError: type object 'FileUploadView' has no attribute 'get_extra_actions' I realized that (well I think) that I can use APIView for FileUploadView (and add ".as_view()) but I think I have to rewrite UniquePostViewSet using APIView as well and defining exactly what I want to see in details like POST, PUT etc... My question … -
How do I build a voice message app in Django? I am a beginner in Django and only know the basics. Where do I start?
I want to buid a voice message app, plan to build on Django, but I am a beginner in Django, how do I start the project? Django is suitable for this project? -
How do I fetch the row associated with the currently logged in user in django and display specific fields in template?
I have a table account that is tied up to the User model by a One to One relationship in django, this account table is meant to store additional information related to the users in the User model. I want to fetch the row in account table of the current user that is logged in/active and display specific data of the user like "designation" or "ac_type" in my template. models.py class account(models.Model): username=models.ForeignKey(User, on_delete=models.CASCADE) first_name=models.CharField(max_length=100) ac_type=models.CharField(max_length=100) designation=models.CharField(max_length=100) drone_id=models.ForeignKey(asset,null= True, on_delete=models.CASCADE) def __str__(self): return self.first_name views.py def dashboard(request): as_data = asset.objects.filter(status=True) #where context = {'as_data':as_data} return render (request, 'dashboard.html',context) def dash_2(self): u=self.request.user ac_data = account.objects.filter(id__in=u).values() context2 = {'ac_data':ac_data} return render (self, 'dashboard.html',context2) dashboard.html <html> <body> My designation is: <br> <p>{{ac_data.designation}}</p> </body> </html> I am a newbie in django so any help would be really helpful. Thanks in advance ! -
Django search form, disambiguation page
Hello everybody I keep having this problem with my search form in my website. The thing is that, based on the user input, i check if in the database there're some results. But if the input is both in band column and album colum I'd like the user to be redirected to a 'disambiguation' html page. This is my views.py but it doesn't work. Hope someone could help me, thanks! Views.py class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sr = Info.objects.filter(Q(band__icontains=srch)) sd = Info.objects.filter(Q(disco__icontains=srch)) if sr is sd: return render(self.request, 'search/disambigua.html') else: paginator = Paginator(sr, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(self.request, 'search/searches.html', {'sr':sr, 'sd': sd, 'page_obj': page_obj }) else: return render(self.request, 'search/searches.html') -
the value inside the class modal-body is showing only the first object of the Django model 'hostels'
the value inside the class modal-body is showing only the first object of the Django model 'hostels' , but when 'edit' in this code is replaced with {{hostel.hostel_name}} its working fine. what's the issue {% for hostel in hostels %} <div class="container" style="width: 48%;margin: 10px;height: 140px;background-color: white;display: inline-block;position: relative;"> <a href="{{hostel.pk}}/deletehostel/" style="color: white;position: absolute;top: 0px;right: 0px;margin: 0px;padding: 0px;padding-right: 5px;padding-left: 5px;background-color: red"> X </a> <a href="{{hostel.pk}}" style="text-decoration: none"> <h1 style="text-align: center;">{{hostel.hostel_name}}</h1> <p style="text-align: center;">total beds: {{hostel.capacity}}</p> </a> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter" style="display: block;margin: auto">edit</button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Edit details here</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <input type="text" class="form-control" value="{{hostel.hostel_name}}" name="" placeholder="hostel name"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> {% endfor %}