Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CAS django - how to send username and password directly without redirecting to CAS server -
i'm using this code from django.http import HttpRequest, HttpResponse from .signals import cas_user_authenticated_callback import json from rest_framework.response import Response from django_cas_ng.views import LoginView from .ldap import get_LDAP_user from datetime import timedelta from importlib import import_module from urllib import parse as urllib_parse from django.conf import settings from django.contrib import messages from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.core.exceptions import PermissionDenied from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect from django.utils import timezone from django.utils.decorators import method_decorator from django.utils.translation import gettext_lazy as _ from django.views import View from django.views.decorators.csrf import csrf_exempt from django_cas_ng.models import ProxyGrantingTicket, SessionTicket from django_cas_ng.signals import cas_user_logout from django_cas_ng.utils import ( get_cas_client, get_protocol, get_redirect_url, get_service_url, get_user_from_session, ) SessionStore = import_module(settings.SESSION_ENGINE).SessionStore __all__ = ['LoginView', 'LogoutView', 'CallbackView'] def clean_next_page(request, next_page): """ set settings.CAS_CHECK_NEXT to lambda _: True if you want to bypass this check. """ if not next_page: return next_page is_safe = getattr(settings, 'CAS_CHECK_NEXT', lambda _next_page: is_local_url(request.build_absolute_uri('/'), _next_page)) if not is_safe(next_page): raise Exception("Non-local url is forbidden to be redirected to.") return next_page def is_local_url(host_url, url): url = url.strip() parsed_url = urllib_parse.urlparse(url) if not parsed_url.netloc: return True parsed_host = urllib_parse.urlparse(host_url) if parsed_url.netloc != parsed_host.netloc: return False if parsed_url.scheme != parsed_host.scheme and parsed_url.scheme: return False url_path = parsed_url.path if parsed_url.path.endswith( '/') … -
Why is the password stored in a raw format to the database in Django? [closed]
I have this Serializer: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): name = validated_data['name'], id = validated_data['id'], user = Person.objects.create(name=name, password=validated_data['password'], id=id) return user I thought that passwords are automatically saved as hashs in the database but with this serializer the password is saved in a raw format. How could I modify this to save the hash, not the raw version? -
Matplotlib unaligned values and names of graphs
Good day! I am making a django app that would plot graphs from a text document. In the text document data is aligned this way: name 10 name_2 20 name_3 100 typeofthegrah I just split everything by spaces and put in 2 lists (names and values), then I just do plt.bar(names, values) and get something like this name1 189 name2 149 name3 23 name4 82 name5 245 name6 90 column I tried sorting them with zip but it didn't work. It works perfectly if I plot it as a pie chart but linear and bar graphs are broken. -
href in <a> tag not working inside <li> DJANGO
href in a tag inside li don't woriking. It does not redirect me to /sub1/. This is my code: body, html { margin: 0; font-family: Arial, sans-serif; font-size: 1em; } .navbar { width: 100%; background-color: #4682B4; height: 80px; color: #fff; } .navbar .nav { margin: 0; padding: 0; float: left; list-style-type: none; } .navbar .nav li.nav-item { float: left; margin: 0 95px; } .navbar .nav li.nav-item>a { display: inline-block; padding: 15px 20px; height: 50px; line-height: 50px; color: #fff; text-decoration: none; } .navbar .nav li.nav-item>a:hover { background-color: #B0C4DE; } .dropdown a:focus { background-color: #B0C4DE; } .dropdown a:focus~.dropdown-container { max-height: 500px; transition: max-height 0.5s ease-in; -webkit-transition: max-height 0.5s ease-in; -moz-transition: max-height 0.5s ease-in; } .dropdown-container { position: absolute; top: 80px; max-height: 0; overflow: hidden; background: #4682B4; color: #B0C4DE; } .dropdown-container a { color: #fff; text-decoration: none; } .dropdown-menu { margin: 0; padding: 0; list-style-type: none; } .dropdown-menu li a { display: inline-block; min-width: 250px; padding: 15px 20px; border-bottom: 1px solid #333; } .dropdown-menu li a:hover { text-decoration: none; background: #B0C4DE; } <body> <nav class="navbar"> <ul class="nav" id="primary-nav"> <li class="nav-item"><a href="/index/">Home</a></li> <li class="nav-item dropdown"> <a href="#">Servicios</a> <div class="dropdown-container"> <div class="dropdown-inner"> <ul class="dropdown-menu"> <li class="dropdown-menu-item"><a href="/sub1/">Submenu 1</a></li> <li class="dropdown-menu-item"><a href="#">Submenu2</a></li> </ul> </div> </div> </li> … -
update_or_create still creates duplicates after unique together
@require_http_methods(["POST"]) @login_required def edit_guided_answer(request): req = json.loads(request.body) question_no = req["question_no"] guided_answers = req["guided_answer"] for guided_answer in guided_answers: models.ModelAnswer.objects.filter(pk=question_no).update_or_create( question_id=models.Questions.objects.get(pk=question_no), answer_mark=guided_answer["answer_mark"], model_ans=guided_answer["model_ans"],, ) return success({"res": True}) class ModelAnswer(models.Model): question_id = models.ForeignKey( Questions, on_delete=models.CASCADE, db_column="question_id" ) answer_id= models.AutoField(primary_key=True) answer_mark = models.FloatField() model_ans = models.TextField(null=True) class Meta: unique_together = (('model_ans', 'answer_mark' ),) db_table = 'MODEL_ANSWER' Update_or_create still makes duplicate entries even after putting unique_together for model_ans and answer_mark is there something that i am missing and is there a way to set a condition so that i can check for duplicates -
Reload virtual enviroment In django
I'm at my first experience with django and I'm having already a little obstacle: I've menaged to create and use a virtual enviroment successufully yesterday, but today I can't seem to be able to reload it. This is how I'm doing it: cd /c/website python -m venv virt spurce virt/scripts/activate cd /c/website/project python manage.py runserver And this is the error I'm getting Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (virt) before doing some mistakes, do I need to reinstall django everytime or I'm just messing up the procedure to reload the ve I created? Thanks for your help! -
Django and Bootstrap columns
I want to create a row with 3 columns using Bootstrap and Django dynamic content that I want to get in those columns. However, with the code below, my content goes one below the other for some reason. Any help is appreciated. 🙏 {% extends 'base.html' %} {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-lg-4 col-sm-12"> {% for post in object_list %} {% if post.is_on_home_page is True %} <a href="{% url 'categories' post.category.slug %}"> {{ post.category }} </a> {% if post.home_or_category_image %} <img class="img-fluid" src="{{ post.home_or_category_image.url }}"> {% endif %} {{ post.author }} <a href="{% url 'article-detail' post.slug %}"> {{ post.title }} </a> {{ post.snippet }} {% endif %} {% endfor %} </div> </div> </div> {% endblock %} -
How to authenticate wordpress wp_remote_post() while sending data to django API view
I am sending some JSON data using wp_remote_post() in wordpress to another django API view, and I'm able to send the data but don't know how to build some security authentication during this wp_remote_post() and django communication. wp_remote_post( 'target url', data ); -
DRF How to use the same variables for multiple functions in test classes?
gal I need to use global variables (class instances) in order to implement them in suitable functions. class MyTests(APITestCase): my_data = 'xxx' User.objects.create(username='any',email='any@g.com',passowrd='pass',) lg_res = client.post('/users/login/', login_data, format='json') client.credentials( HTTP_AUTHORIZATION=f'Bearer {lg_res.data["access"]}') def test_one(self): self.client(bla bla bla) print('======================') print(self.my_data) ##this is fine it work print('======================') def test_two(self): # I need here to login the same user again self.client(bla bla bla2) problems When I when I create new user inside the functions it work very fine Also, I am not sure how to add client credentials outside the functions,I assume somthings like Class MyTests(APITestCase): client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: users_user.email -
How to add a second password to a Django user account for a secured area
I would like my users to have two passwords, the normal login password and one for accessing more secure areas of the site. I would like to rely on the existing Django authentication system as much as possible for this. I am picturing logging in to a secure area with this password would enable a "secure mode" with a fairly short timeout, similar to how sudo does not ask for a password for a while after use in some linux distros. So it would add a flag and a timestamp to the user session. I assume achieving this would involve replacing the default User model with a subclass with an extra password field and some kind of custom middleware, however I have not customised Django auth before and I'm not sure where to start. I am also open to alternate suggestions for how to manage the secure area. -
Django rest framework AttributeError after GET request
During a GET request, Django give me this error: Got AttributeError when attempting to get a value for field `name` on serializer `projectSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `ProjectTask` instance. Original exception text was: 'ProjectTask' object has no attribute 'name'. I'm pretty new to django and rest_framework, here's the code: models.py class Project(models.Model): name = models.CharField(max_length=50) class ProjectTask(models.Model): project = models.ForeignKey(Project,on_delete=models.CASCADE) description = models.CharField(max_length=200) status = models.IntegerField() serializers.py class projectTaskSerializer(serializers.ModelSerializer): class Meta: model = ProjectTask fields = ['description','status'] class projectSerializer(serializers.ModelSerializer): tasks = projectTaskSerializer(many=True) class Meta: model = Project fields = ['name','tasks'] views.py (I'm only mentioning the get function that is being called to avoid cluttering the question def get(self, request): projects = ProjectTask.objects.all() serialized_projects = projectSerializer(projects,many = True) return Response({'projects' : serialized_projects.data}) -
Django AllAuth Facebook: Cant login: Social Network Login Failure An error occurred while attempting to login via your social network account
I have been using Django AllAuth to login to my Django App on my localhost before. It had been working fine then suddenly today I started getting this message when trying to login via Facebook : Social Network Login Failure An error occurred while attempting to login via your social network account. These are the configs for my FB App: FB App Config FB App Config 2 FB App Config 3 FB App Config 4 FB App Config 5 FB App Config 6 My Django AllAuth Config: Django AllAuth Config Please suggest how I can fix this and get AllAuth working. If you have any other suggestions, or alternatives, its greatly appreciated. Thanks! -
Unable to render a template after using fetch in django
I have the following requirement: Send data to backend using fetch() receive the data in a view and render another template ( route to a different view) The following is my code snippet: JS: fetch("/addpost", { method: "POST", body: JSON.stringify({ value: selecteddict }), headers: { "Content-type": "application/json;", }, }) .then((res) => { return res.text(); }) .then((text) => { console.log(text); }); // the data is being sent successfully Django View1: @csrf_exempt def addpost(request): if request.method == 'POST': song = json.loads(request.body.decode('utf-8'))['value'] print(song) # I want to redirect to another view called createpost that renders a new page return JsonResponse({'status':201}) return render(request, 'addpost.html') Django createpost view: def createpost(request): return render(request, 'createpost.html') The view createpost is working fine when given the required path but it is not rendering when it's redirected from addpost Please suggest a solution to this. -
How to redirect to a url with parameters in django while using 'return redirect()' from inside a view?
I looked up this question on stack overflow and all the previous related answers are very old which seem to no longer work in newer versions of django . Basically I have a url : urlpatterns = [ .... path('proudct-settings/<int:product_id>',views.product_settings, name="product_settings"), .... ] How do I redirect to this url from this view : @login_required def remove_discount(request, product_id): product = Product.objects.get(id=product_id) product.discount_flag = False product.discount_amount = 0 product.price = product.original_amount product.save() # this return statement for redirecting to url isnt working when I pass the parameter like this return redirect('product_settings',product_id) How can I achieve this redirection to url with parameters using redirect from inside the view ? -
How to get the fields of a django model?
I am creating an API that takes the fields of a model. Say from django.db import models class Student(models.Model): name = models.CharField(max_length=24) age = models.IntegerField() address = models.CharField(blank=True) I want to make an API that takes argument something like this. from typing import Optional from dataclasses import dataclass from models import Student from django.forms.models import model_to_dict @dataclass class RequestStructure: name: str age: int address: Optional[str] def createStudent(req:StudentInfo) -> StudentInfo: data = Student.objects.create(name=req.name, age=req.age, address=req.address) return {"data": model_to_dict(data)} The above code will work fine, but there I have to define the same type for Student which I have already defined in the model. Can I use the model definition as the param type annotation instead of defining it again? -
React Native - display styled text from Django RichTextUploadingField
on my mobile app I would like to display styled text from my database. Im using Django and CKEditor to create styled description. description = RichTextUploadingField(blank=True, config_name='special') Now in my react native app let's say I display this description: <Text>{description}</Text>. Unfortunately this text is not styled. Is there any simple library or method which allows to display this text in proper way? I tried libraries like react-native-ckeditor, but it wasn't working -
How to handle migrations in Django project in production (Digital Ocean App Platform)?
I have been using the app platform for almost 2 months. Yesterday, I made some changes in database tables (models) in my Django projects. I pushed those changes to Github and my app successfully redeployed. But When I open the site, I got “ProgrammingError” that some field that I created new in the existing table does not exist. So, I opened the console in App Platform and applied migrations but nothing is changed. I am still facing the error. Exception Type: ProgrammingError Exception Value: column productssubcategory.description does not exist LINE 1: …subcategory".“id”, “productssubcategory”.“name”, “products_… -
Django: trigger function in views.py from Javascript
I want to trigger a function that downloads a file from my "views.py", the trigger is in a "javascript" function: ---BROWSER (JAVASCRIPT)--->ONCLICK--->DOWNLOAD A FILE (DJANGO STATIC FILE) I have managed to call my django views functions from javascript using AJAX before, but it was always for getting HTTPRESPONSE,nothing involved downloading files. Also my view function downloads with no problems. But the problem is the JAVASCRIPT wrapper: <div id="smart-button-container"> <div style="text-align: center;"> <div id="paypal-button-container"></div> </div> </div> <script src="https://www.paypal.com/sdk/js?client-id=sb&currency=xxx" data-sdk-integration-source="button-factory"></script> <script> function initPayPalButton() { paypal.Buttons({ style: { shape: 'pill', color: 'gold', layout: 'horizontal', label: 'xxx', }, createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{"description":"xxxx{"currency_code":"xxx","value":xxx}}] }); }, onApprove: function(data, actions) { return actions.order.capture().then(function(details) { alert('Transaction completed by ' + details.payer.name.given_name + '!'); }); }, onError: function(err) { console.log(err); } }).render('#paypal-button-container'); } initPayPalButton(); </script> I would like to know the answer to this problem. -
How to send Petitions Multi Thread Python / Django
I'm using Django and I need to send many requests, there is any way to send it on multi-thread? This is my code. def send_ws_info(serializer, id): url = f'{settings.WS_URL}/notify/{id}' token, created = Token.objects.get_or_create(user__id=id) headers = {'Authorization': f'Token {token.key}'} requests.post(url=url, json=serializer, headers=headers) -
How to code 'Dynamic' generic based view with Django?
I've develop a first eCRF app (project 1) using Django and now I want to make it more "generic" because most of the code is duplicated I've to make views, forms and templates generic based on available models I've read some post (Is it bad to dynamically create Django views?) with urls config and as_view() override parameters but I need to override get_context_data() and get_form_kwargs() methods so I think I can't use urls config all my views looks like below: InclusionCreate, InclusionUpdate, VisiteCreate, VisiteUpdate, etc... How can I acheive this? views.py @method_decorator(login_required, name='dispatch') class InclusionCreate(SuccessMessageMixin, CreateView): model = Inclusion form_class = InclusionForm template_name = "ecrf/inclusion_form.html" success_message = "La fiche Inclusion a été créée." def get_success_url(self): return reverse('ecrf:patient', args=[self.kwargs['pk']]) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form_name"] = 'inclusion' return context def get_form_kwargs(self): kwargs = super(InclusionCreate, self).get_form_kwargs() kwargs['patient'] = Patient.objects.get(ide = self.kwargs['pk']) kwargs['user'] = self.request.user return kwargs @method_decorator(login_required, name='dispatch') class InclusionUpdate(SuccessMessageMixin, UpdateView): model = Inclusion form_class = InclusionForm template_name = "ecrf/inclusion_form.html" # nom template à utiliser avec CBV : [nom_model]_form.html success_message = "La fiche Inclusion a été modifiée." def get_success_url(self): return reverse('ecrf:patient', args=[Patient.objects.get(pat = Inclusion.objects.filter(ide = self.kwargs['pk']).first().pat.pat).ide]) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) patient = self.request.session.get('patient') context["form_name"] = 'inclusion' context["ide"] = self.kwargs['pk'] … -
Accessing Statics Files in Django
I am having a structure of Django Project as: │ db.sqlite3 │ manage.py │ ├───static │ │ 1.jpg │ │ bg1.jpg │ │ │ └───css │ login.css │ ├───templates │ home.html │ login.html │ register.html │ ├───User │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ __init__.cpython-38.pyc │ │ │ └───__pycache__ │ admin.cpython-38.pyc │ apps.cpython-38.pyc │ models.cpython-38.pyc │ urls.cpython-38.pyc │ views.cpython-38.pyc │ __init__.cpython-38.pyc │ └───Website │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───__pycache__ settings.cpython-38.pyc urls.cpython-38.pyc wsgi.cpython-38.pyc __init__.cpython-38.pyc Settings.py """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-c*3$w_63@$^8g&_fn%r=-23n^e@nrmxzxt7eh*owsz^mlrk5dr' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'User' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = … -
How do I find out the last object in a sliced queryset list at django?
How do I find out the last object in a sliced queryset list at django? Even if I use last() and first() in the queryset list, the following error occurs. Cannot reverse a query once a slice has been taken. I created a queryset list by putting the condition as below. comment = Comment.objects.filter(is_deleted=False,parent=None).order_by('-created_at')[:10] and here is comment <QuerySet [<Comments: Comments object (149)>, <Comments: Comments object (148)>, <Comments: Comments object (147)>, <Comments: Comments object (146)>, <Comments: Comments object (145)>, <Comments: Comments object (144)>, <Comments: Comments object (143)>, <Comments: Comments object (142)>, <Comments: Comments object (141)>, <Comments: Comments object (140)>]> i want to get <Comments: Comments object (140)> How do I find out the last object in a sliced queryset list at django? -
BoundField' object has no attribute 'replace
I am trying to make a filter that when the user mention users, I try to open this accounts that have @ For Example, if there are @Users this mention convert to link like Twitter. My Filter That raise this error 'BoundField' object has no attribute 'replace' import re from django import template register = template.Library() def open_account(text): try: results = re.findall("(^|[^@\w])@(\w{1,20})") for result in results: result = result[1] except: pass return text.replace(result, '<a target="_blank" style="color: blue;"') url_target_blank = register.filter(open_account, is_safe = True) -
Django - (Tagulous) AttributeError: type object 'Model' has no attribute '_meta'
I'm trying to learn as much as possible myself with regards to discovering solutions to my challenges, but this error has got me stuck a little! (I am currently trying to implement Tagulous in to my app) At the point of running a migration, I am receiving the following error: AttributeError: type object 'Model' has no attribute '_meta' Here is the code I have implemented so far whilst referencing the Tagulous tutorials Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from PIL import Image import tagulous.models class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) image = models.ImageField(default='default.png', upload_to='media') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.content[:5] img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() class Comment(models.Model): content = models.TextField(max_length=150) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, on_delete=models.CASCADE) class Preference(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) post= models.ForeignKey(Post, on_delete=models.CASCADE) value= models.IntegerField() date= models.DateTimeField(auto_now= True) def __str__(self): return str(self.user) + ':' + str(self.post) +':' + str(self.value) class Meta: unique_together = ("user", "post", "value") class Skill(tagulous.models.TagTreeModel): class TagMeta: initial = [ "test1", "test2", "test3", ] space_delimiter = False autocomplete_view = … -
ValueError at /checkout/ The QuerySet value for an exact lookup must be limited to one result using slicing
ValueError at /checkout/ The QuerySet value for an exact lookup must be limited to one result using slicing. Request Method: GET Request URL: http://127.0.0.1:8000/checkout/ Django Version: 3.2.3 Exception Type: ValueError Exception Value: The QuerySet value for an exact lookup must be limited to one result using slicing. Error Screenshot Error This line is causing issue APP views.py Checkout @login_required def checkout(request): if request.user.is_authenticated: name = request.user print(name) order=Orders(customerID=name) order.save() cart = Cart(request) for items in cart: print(items) OrderDetails(orderID=order,productID=items['product'],quantity=items['quantity'],price=items['total_price']).save() order = Orders.objects.filter(customerID=name) OrderDetail = OrderDetails.objects.filter(orderID=order) customerDetails = Customer.objects.filter(user=name).count() print(customerDetails) return render(request, 'app/checkout.html',{'orders':OrderDetail,'address':customerDetails}) CheckOut Template {% extends 'app/base.html' %} {% load static %} {% block title %}Buy Now{% endblock title %} {% block main-content %} <div class="container"> <div class="row mt-5"> <div class="col-sm-6"> <h4>Order Summary</h4> <hr> {% for order in orders %} <div class="card mb-2"> <div class="card-body"> <h5>{{order.name}}</h5> <p>Quantity: {{order.quantity}}</p> <p class="fw-bold">Price: {{order.price}}</p> </div> </div> {% endfor %} <small>Term and Condition: Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia, ullam saepe! Iure optio repellat dolor velit, minus rem. Facilis cumque neque numquam laboriosam, accusantium adipisci nisi nihil in et quis?</small> </div> <div class="col-sm-4 offset-sm-1"> <h4>Shipping Address</h4> <hr> {% for ad in address %} <div class="card"> <div class="card-body"> <h5>{{ad.name}}</h5> <p>{{ad.address}}</p> <p>{{ad.phone}}</p> </div> {% …