Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it OK to use daphne as a production server in this situation?
I need to deploy a server with django rest framework, django-channels. It is used in-house and distributed for the Windows OS. It is a small-scale server with about 10~20 users. Is it OK to use daphne (without nginx, apache, etc..) as a production server that serves both asgi and rest api in this situation? -
How does formset function work for django-extra-views?
I am using the package django-extra-views to create inline forms. I want some help in understanding the working of formset function we use in javascript code while working with django-extra-views. How does it add 'Add Another' and 'Remove' link in the formset? I have taken help from Using django-dynamic-formset with CreateWithInlinesView from django-extra-views - multiple formsets In my views.py: class PriceDetailsInline(InlineFormSetFactory): model = models.PriceDetails form = forms.PriceDetailsForm fields = '__all__' factory_kwargs = {'extra': 1, 'can_delete': False} class CreateInvoiceView(LoginRequiredMixin, CreateWithInlinesView): model = models.Invoice form = forms.InvoiceForm inlines = [PriceDetailsInline] fields = '__all__' template_name = 'app/invoice_form.html' In my invoice_form.html: <table> {{ form.as_table }} </table> {% for formset in inlines %} <div id="{{ formset.prefix }}"> {% for subform in formset.forms %} <table> {{ subform.as_table }} </table> {% endfor %} {{ formset.management_form }} </div> {% endfor %} {% block extra_footer_script %} <script type="text/javascript"> $(function() { {% for formset in inlines %} $('div#FormSet{{ formset.prefix }}').formset({ prefix: '{{ formset.prefix }}', formCssClass: 'dynamic-formset{{ forloop.counter }}' }); {% endfor %} }) </script> {% endblock %} The code is working fine but I need to understand the flow in order to make changes to the 'add another' and 'remove' link and to apply crispy to the dynamically added forms. -
Django logging - default value of custom field in formatter
I am using below log formatter in my django app for keeping track of what class the logline belongs. 'format' : "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s:%(classname)s()] %(message)s" In this classname is custom field and I am accessing it as below. Sometimes I am collecting the logs from function that doesnt belongs to any class. In that case, I have to send logline with classname as 'NA' import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger('django') # .......... SOME CODE ........ #Exception occurred inside class function log.error("EXCEPTION !!",extra={'classname': self.__class__.__name__}) # .......... SOME CODE ........ #Exception occurred in standalone function log.error("EXCEPTION in function !!",extra={'classname': "NA"}) Is there a way to put default value of classname as NA in formatter ? -
I can't register user in my user registration form
I have created a user registration form, every thing looks fine but when I try to register new user it brings back the same form while I redirected it to home page. Also when I go to admin to look for new registered user, I see nothing This is for python 3.7.3, django 2.2.3 and mysql 5.7.26. I have tried to check and recheck every thing seems to be ok but still I can't achieve what I want forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username","email","password1","password2") views.py def register(request): if request.method == "POST": user_form = NewUserForm(request.POST) if user_form.is_valid(): user = user_form.save() login(request, user) return redirect("loststuffapp:IndexView") else: for msg in user_form.error_messages: print(user_form.error_messages[msg]) user_form = NewUserForm return render( request, "loststuffapp/register.html", context={"user_form":user_form} ) register.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <button type="submit" style="background-color: yellow">Register</button>> If you already have an account, <a href="/Register">login</a> instead {% endblock %} -
Could you please explain the add to cart view I have mentioned here?
I am following a tutorial for building my first e-commerce application. I am kinda stuck on his add to cart view. Kindly help me explain some code line in detail in that view which I don't understand. I will be writing the word "Detail" before the line of code I want to understand in detail. Here's the view def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) Detail -- Why does the code filter order since this view is about order item not order order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] Detail -- Hint: Why it filters and where does this items come from and what query is in filter I don't known since it's repeating it if order.items.filter(item__slug=item.slug).exists(): Detail --- Why do we have to increase the quantitiy here order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: Detail --- why will we add it since it has to be in the card only order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") Detail -- and what is written in this else why create the order and do unnecessary stuff else: ordered_date = timezone.now() order … -
Place Primary key inside JSON response
The JSON response i'm getting is as below. In my code i'am trying to fetch the list from the db, as per above img. In the result primary key is coming outside of the fields for each record. How can i place it inside the fields for every record like. "results":[ "fields":{ "pk": "F09087687633", "company_name": "Tata", } ] Below is my code: views.py (In below code for loop is to remove app name from the results, same i use to remove primary key, it is working but how can i place it inside for each fields.) @csrf_exempt def fleet_owner_list(request): page_number = json.loads(request.body) records,total_pages = FleetOwner.get_all_owners(page_number) for data in range(len(records)): del records[data]['model'] returnObject = { "page" : page_number, "total_results":len(records), "total_pages":total_pages, "status" : messages.RETRIVAL_SUCCESS, "message" : messages.FLEETOWNER_DATA_RETRIEVE_SUCCESS, "results" : records } models.py @classmethod def get_all_owners(cls,page_number): data = cls.objects.filter(is_deleted = False) page_numbers = page_number pegination_result, total_page_count = list_paginate(data, page_numbers) data = serializers.serialize("json", pegination_result) data = json.loads(data) return data, total_page_count paginator.py (This is a common function i'm using for all the list functions to perform django pagination.) def list_paginate(data,page_numbers): paginator = Paginator(data,10) page = page_numbers try : records = paginator.page(page) except PageNotAnInteger: records = paginator.page(1) except EmptyPage: records = paginator.page(paginator.num_pages) return records, paginator.num_pages pegination_result, … -
Django project is creating into C:\VTRoot\HarddiskVolume3 by default
I am putting "django-admin startproject mysite". Project is creating in the folder of C:\VTRoot\HarddiskVolume3 by default instate of desire folder. Please help me out. pip install django -
How to get red of 'Apps aren't loaded yet' in django whenever I run the code?
It is just a simple question but I posted full code. I am trying to make a search bar working in django. I wrote code which I am going to show you but whenever I run the code it gives me the following error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I really want to know how to solve this issue? I am posting this question twice okay due to posting issue. It is just a simple question but I posted full code. I am trying to make a search bar working in django. I wrote code which I am going to show you but whenever I run the code it gives me the following error. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I really want to know how to solve this issue? I am posting this question twice okay due to posting issue. <body> <div class="container"> <h1>Search Students Information</h1> <form method="post" action="/search/"> {% csrf_token %} <div class="form-group"> <div class="col-lg-5"> <input type="text" name="srh" class="form-control" placeholder="Enter...."> </div> <label class="col-lg-2"> <button type="submit" class="btn btn-danger"> Search </button> </label> </div> </form> <div> search.html {% if messages %} <ul class="messages"> {% for k in messages %} <li style="color:red">{{k}}</li> {% endfor %} </ul> {% endif %} </div><br> <div style="color: blue"> … -
Function SIMILARITY does not exist. Module pg_trgm already exists... How can I clear this error?
After installing PostgreSQL I keep getting an error. "LINE 1: ...T COUNT() FROM (SELECT "blog_post"."id" AS Col1, SIMILARITY...*" HINT: No function matches the given name and argument types. You might need to add explicit type casts. sudo apt install postgresql-contrib psql# CREATE EXTENSION pg_trgm; sudo service postgresql restart (venv) dev-py@devpy-VirtualBox:~/Dev/mysite/mysite$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 12, 2019 - 20:31:19 Django version 2.2.3, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [12/Jul/2019 20:31:32] "GET /blog/search/ HTTP/1.1" 200 995 Internal Server Error: /blog/search/ Traceback (most recent call last): File "/home/dev-py/Dev/mysite/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: function similarity(character varying, unknown) does not exist "LINE 1: ...T COUNT() FROM (SELECT "blog_post"."id" AS Col1, SIMILARITY...*" HINT: No function matches the given name and argument types. You might need to add explicit type casts. Any help would be appreciated. It took me 3 days of troubleshooting this before I asked for help but I am sure someone knows the answer and it's simple. If you need any more info please just lmk. -
How do I include a variable in static content in Django template?
I am running Django 2.2.2 attempting to load static conytent whose name is given by a template variable. For a fixed name I can successfully use (for example): however if I try replacing "AS" with the value of a variable, {{ card }}: when I look at the generated HTML the alt tag is expanded as expected but the src tag is URL-escaped: I have tried various placements of the quotes but either get a result like this or a template parsing error. The desired output is (assuming card = AH): -
Django: Paginating Postgres Search Results
I have this tool for searching friends but my pagination returns a bunch of random results. The first page is always relevant to the search terms, so I know it's the pagination that's the problem. What am I doing wrong here? When I paginate to page 2 via ?q=something&page=2 the results appear to be all random (unfiltered results). class PeopleSearchView(LoginRequiredMixin, generic.ListView): context_object_name = 'snapshots' redirect_field_name = "next" paginate_by = 15 def get(self, request, *args, **kwargs): if request.GET.get('q') == None: return HttpResponseRedirect(reverse('people:friends')) return super(FriendsSearchView, self).get(request,*args,**kwargs) def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['query_string'] = self.request.GET.get('q') return context def get_queryset(self): query_string = self.request.GET.get('q') vector = SearchVector('description', weight='A') + SearchVector('location', weight='A') + SearchVector('name', weight='B') query = SearchQuery(query_string) return PeopleSnapshot.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank') -
Modify and display context with output from a form
using a django form, im taking user input in the form of a url, and sending a request to that url. what i want to do is parse out the status code of the response, and add it to the context dictionary and display it in the template. i typically send a request and parse the response as follows: import requests url = input('what url?') response = requests.get(url) stat_code = str(response.status_code) print(stat_code) but since im trying to do this with django, this now involves form.py to take the url as user-input, as well as view.py logic and template.html to display it. project/app/forms.py class SearchForm(forms.Form): def send_request(self): response = api.execute('findCompletedItems', dct_request) stat_code = response.status_code return stat_code project/app/views.py class SearchView(FormView): template_name = 'search.html' form_class = SearchForm success_url = 'results' context_object_name = 'item' def form_valid(self, form): form.get_sales_history() return super().form_valid(form) def get_context_data(self): context = super(SearchView, self).get_context_data() context['stat_code'] = stat_code return context but there is no visible output. project/templates/results.html <h1>{{ item.stat_code }}</h1> ive been trying to figure this out literally all day long, and ive tried lots of different things. i got everything to work except for the actual displaying of the response data stat_code. i sincerely apologize if this is a jumbled mess, as … -
I'm new to Django framework and I'm having an error "ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package"
I'm creating an app directory for web scraping which is scrape inside my django_project. I'm having an an error in importing a class from my models.py module into my views.py module. Here's my code in models.py from django.db import models # Create your models here. # model -- headline (title, url, date) class Headline(models.Model): title = models.CharField(max_length=120) url = models.TextField() event_date = models.TextField() def __str__(self): return self.title and this code in views.py from django.shortcuts import render, redirect import requests requests.packages.urllib3.disable_warnings() from bs4 import BeautifulSoup from .models import Headline # Create your views here. def scrape(): # Use the session to get the URL session = requests.Session() url = 'https://allevents.in/malacca/all?ref=cityhome-popular' # Content is basically grabs all the HTML that comes from the session content = session.get(url, verify=False).content soup = BeautifulSoup(content, "html.parser") # Return a list #item = soup.find_all('div', class_="event-item") for item in soup.find_all('div', class_="event-item"): title = item.find("h3").text.strip() linkhref = item.find("h3").find("a").get('href') date_posted = item.find("div", {"class":"right"}) new_headline = Headline() new_headline.title = title new_headline.url = linkhref new_headline.event_date = date_posted new_headline.save() return redirect('/event/') after try run python views.py from cmd this error is appeared Traceback (most recent call last): File "views.py", line 5, in <module> from .models import Headline ModuleNotFoundError: No module named '__main__.models'; '__main__' … -
Is there a way to move to the bottom using jquery animate scroll?
Is there a way to move to the bottom using jquery animate scroll? ex $(".go_btn").click(function(){ const number = $(".go_input").val(); if(number == 1){ $('html, body').animate({ 'scrollTop' : $("#index_first").offset().bottom }); } $('html, body').animate({ 'scrollTop' : $("#index_"+number).offset().top }); }) and is this possible? 'scrollTop' : $("#index_first").offset().bottom + 10px up very thank you for let me know ~!~! -
Django , how to find the difference for two given tables SQLite DB
Given two entities of the same table and would like to find the difference between them in an effective way -
How to make custom UserCreationForm for admin page for custom user?
How to make custom UserCreativeForm for admin page? I tried this but it doesn't work. my models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, unique=True, blank=True, null=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField( _('staff status'), default=False, ) my forms.py: from django.contrib.auth import get_user_model User = get_user_model() class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') phone = forms.CharField(label="Phone number", required=False, max_length=15, help_text='Required. Inform a valid phone number.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'phone', 'password1', 'password2', ) admins.py: class CustomUserAdmin(UserAdmin): add_form = SignUpForm model = CustomUser list_display = ['email', 'username', 'phone', ] admin.site.register(CustomUser, CustomUserAdmin) How to make custom UserCreativeForm for admin page? I tried this but it doesn't work. -
Ngnix Not Serving Static Files In Production
I keep getting 404 Not Found Error when i try to load any static file from my project even after collecting staticfiles. I tried changing some of the configuration in settings.py and NGINIX config too, but nothing seems to be working NGINIX CONFIG server { listen 80; server_name 134.209.169.204; location = /favicon.ico {access_log off; log_not_found off;} location /static/ { root /home/lekan/181hub; } location /media/ { root /home/lekan/181hub; } location / { include proxy_params; proxy_pass http://unix:/home/lekan/181hub.sock; } } SETTINGS.PY STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIR = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I expect the static files to load without any problem, please let me know if there's a problem with my configuration -
Redirect to Google OAuth returns 404 within API test while working in the browser
I am trying to test my API before and after it redirects to Google OAuth but it strangely leads to 404 error. However, when I use the exact same URL in the browser (by copying and pasting), it magically works as usual. Using Django, apart from the tests, it also works fine. Essentially, I tried to use both direct and indirect URLs with varying query strings, yet all in vain. Below, you can find a simple way of replicating the problem. I am using social django and django rest framework. The url redirects to https://accounts.google.com/o/oauth2/auth with an additional query string. from rest_framework.test import APITestCase from rest_framework import status class ClientPath(APITestCase): def test_google(self): url = "/sociallogin/google-oauth2/" response = self.client.get(url, SERVER_NAME="127.0.0.1:8000", follow=True) self.assertEqual(response.status_code, status.HTTP_200_OK) The response says: '<h1>Not Found</h1><p>The requested resource was not found on this server.</p>', however when I try to open the URL including the query string, containing client_id, redirect_uri, response_type and scope (I am not posting it as it contains sensitive information) in the browser, it works. It shows me a typical "Sign in with Google" page. -
Input type Date not have value in page RTL and have value when page LTR
I have project using Django framework and i user i18n to support English and Arabic I have create form for add customers and i use the input type date to pick the date it works fine in LTR but when chane direction to RTL it lost the value when i submit the form the form model: enter code here class patienForm(forms.ModelForm): class Meta: model = patientModel fields=['Patient_Name_en', 'Email', 'Birth_Date'] widgets = { 'Patient_Name_en': forms.TextInput(attrs={'class': 'form-control'}), 'Email': forms.EmailInput(attrs={'class': 'form-control'}), 'Birth_Date':forms.DateInput(attrs={'class':'form-control','type':'date','max':dt}), } the view : class createPatientView(CreateView): model=patientModel template_name='reception/patientmodel_form.html' form_class=patienForm def form_invalid(self, form): print(form.instance.Birth_Date) print(form.instance.Email) print(form.instance.Patient_Name_en) return HttpResponse(form) def form_valid(self, form): print(form.instance.Birth_Date) print(form.instance.Email) print(form.instance.Patient_Name_en) return HttpResponse(form) the result of the above code : when page is RTL it call form_invalid and print: None alfaifi@fds.com.sa Abdullah Alfaifi when the same page but LRT it call form_valid and print : 2014-07-12 alfaifi@fds.com.sa Abdullah Alfaifi What will be the issue -
How to fix: CORB block for google chrome (Axios request)
I'm using Django with Rest framework and React to make a call to this API url. I already enabled CORS, however, the axios request is still blocked by CORB. Also tried to temporarily disabling it, by starting Chrome with the following command line flag: --disable features=CrossSiteDocumentBlockingAlways,CrossSiteDocumentBlockingIfIsolating componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff' } }).then(res => { this.setState({ article: res.data }); console.log(`http://127.0.0.1:8000/api/${articleID}`); //console.log(res.data); }); } WARNING: Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8000/api/1 with MIME type application/json. -
Django modelform field: when only one option exists, set that option as the default in dropdown
I have a Prescription modelform that lets users (employees at a medical office) create prescriptions. Users must select a "prescriber" for each prescription. "Prescriber" is filtered in views.py to show only prescribers that practice in the user's office. I'm trying to work an if / else statement into the modelform view: if my queryset filter options = only one option, make that the default in the form (appearing as if it has already been chosen in the dropdown, instead of the blank option that appears) I've been going down rabbit holes on SO all afternoon. Please help! Views.py @login_required(login_url="/login") def new_rx(request): if request.method == "POST": form = PrescriptionForm(request.POST) if form.is_valid(): prescription = form.save(commit=False) prescription.status = Prescription_status.objects.get(pk=1) # draft status prescription.medical_office = request.user.medical_office # medical office prescription.save() return redirect('vhome') else: form = PrescriptionForm() form.fields["prescriber"].queryset = CustomUser.objects.filter(medical_office=request.user.medical_office, prescriber=True) return render(request, 'app/new_rx.html', {'form': form}) forms.py class PrescriptionForm(forms.ModelForm): class Meta: model = Prescription fields = ('prescriber', 'medication', 'quantity', 'directions', 'refills', 'earliest_permitted_fill_date', 'daw',) widgets = { 'earliest_permitted_fill_date': DatePickerInput(), # default date-format %m/%d/%Y will be used } -
Getting None values for POST request (via the Axios library) sent to Python/Django
I am building a web app with Django/Python and trying to send data to a controller via a POST request using the Axios library (within Vue.js code). The POST QueryDict seems to be empty and I can't see why that is happening: changeCountry: function(e, id){ console.log("Let's change the country") console.log(e.target.value) // is printing correctly console.log(id) // also printing correctly axios({ method: 'post', url: '/template/country', data: { id: id, country: e.target.value }, headers: { 'X-CSRFToken': "{{csrf_token}}" } }) .then(function (response) { alert(response.data); // this is returning what I expect }) .catch(function (error) { console.log(error); }) }, The Python method looks like this: def update_template_country(request): pprint(request.POST) # prints an empty QueryDict id = request.POST.get('id') country = request.POST.get('country') print(id, country) #prints None None return HttpResponse("The country is changed") # this is being returned back to the client The console.log messages at the top print what I expect and since there is no error I am assuming the CSRF header token is fine. Have I missed something obvious or misunderstood how this is working? -
How to override change model object form?
I am trying to override change model form for adming page but don't know why it doesn't work. Can smb help me please? My forms.py: from django import forms from django.contrib.auth.forms import UserChangeForm from django.contrib.auth.models import User class CustomUserChangeForm(UserChangeForm): email = forms.EmailField(required=True, label="Email") phone = forms.CharField(label="Phone number") class Meta: model = User fields = ("username", "email", "phone", ) My admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'phone', ] admin.site.register(CustomUser, CustomUserAdmin) My models.py class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, unique=True, blank=True, null=True) I am trying to override change model form but don't know why it doesn't work. Can smb help me please? -
Django admin template override does not work on Heroku
I'm try to override the actions.html file found in django/contrib/admin/templates/admin. This is the file I am overriding with. {% extends "admin/actions.html" %} {% block actions-counter %} {% if actions_selection_counter %} <span class="action-counter" data-actions-icnt="{{ cl.result_list|length }}">{{ selection_note }}</span> {% endif %} {% endblock %} I am only trying to override it for a specific model. This change works fine when I run Django on my local development server using the runserver command, but when the project is deployed to Heroku, the changes are not seen and the default template is still displayed. My project hierarchy looks like this project | | __templates | | __admin | | __my_app | | __model | | __actions.html I've also tried arranging it like project | | __my_app | | __templates | | __admin | | __my_app | | __model | | __actions.html Both ways work locally, but not on Heroku. -
how to display several bootstrap cards on the same row
i am trying to display retrieved data from database in cards using bootstrap 4 the data is retrieved correctly but the problem is in the displaying of these cards because it just been displayed on a vertical way each card on a row. what i need is to display let say 3 or 4 cards on the same row. code: {% for obj in object_list %} <div class="container"> <div class="row"> <div class="col-md-4"> <div class="card"> <!--Card image--> <img class="img-fluid" src="https://mdbootstrap.com/img/Photos/Others/images/43.jpg" alt="Card image cap"> <!--Card content--> <div class="card-body"> <!--Title--> <h4 class="card-title">name:{{ obj.name}}</h4> <!--Text--> <p class="card-text">{{obj.content}}</p> <a href="#" class="btn btn-primary">Button</a> </div> </div> </div> </div> </div> {% endfor %}