Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validation/Validation+Creation based on input field in Django Rest Framework
I have my own model, Viewset and Serializer class. My requirement is based on input request's field value i have to perform Validation or Validation+Creation ie if action flag is "Validate", i have to perform validation only and if validations are passed i have to return 204 with no content And if action flag is "Save", I have to perform both Validation and creation. And at the end need to return created entity with status 201. Can any one please help me to implement this in DRF -
how to solve bulk_update() objects must have a primary key set error?
Here from the frontend user gives the input values like this ['1','2', '3']. I want to update the multiple objects at time with bulk_update and I tried like this but this is giving me this error. ValueError: All bulk_update() objects must have a primary key set. class PVariant(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE) .... #views quantity = request.POST.getlist('quantity_available') #['1','2','3'] names = request.POST.getlist('names') fields = ['name', 'price', 'quantity'..] params = zip(names, quantity, weight,..) variants = [PVariant(display_name=param[0],sku=param[1], quantity=param[2], weight=param[3], product=product) for param in params] PVariant.objects.bulk_update(variants, fields) -
Client-Side Verification Django
I'm new to Django and I made a form that extends UserCreationForm and I want to verify the inputs on the client-side. How can I do that? Thanks in advance class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] -
MIME type Error Django/React project on PythonAnywhere
I've used PythonAnywhere before, but this is the first project that utilizes a Django back end and React front end. What is strange is that if I run this exact project on localhost, there are no troubles at all. It is only when I host this website on PythonAnywhere do I get this error. They're probably hard to see... Refused to apply style from 'http://bluebirdteaching.pythonanywhere.com/static/css/2.8aa5a7f8.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Looking this up, I've come across this page a lot, but I just can't seem to make sense of the answers provided there. I just don't understand why this works on localhost, but not on PythonAnywhere. I included the above image not just to show my index.html, but also to show the project directory as that seems to be necessary as the other post linked explains. If the answer I'm looking for is in that other post, I just can't make sense of it. Again, everything works as expected when I run the project locally. Of course, thanks guys for any help. I've been going at this problem for a while now; any help/explanations would be a … -
How to show the string value instead of id in Django Templates?
I have here my codes : views.py chem_inventory_solid = models.ChemInventorySolid.objects.values('solidSubstance').order_by('solidSubstance').annotate(total_kgs=Sum('kgs')) template {% for list in chem_inventory_solid %} <tbody> <tr> <td>{{list.solidSubstance }}</td> <td>{{list.total_kgs}}</td> <td> </td> </tr> </tbody> {% endfor %} output Solid Substance | Total Qty 1 1542 2 2000 How to show the solid substance name instead of id ? -
Using django-embed-video in bootstrap carousal
I am working on a django project. In the project, I have a set of youtube videos That I want to display in a carousal. For displaying the videos, I am using django-embed-video. This is my code for displaying the videos in a template {% for i in videos %} {% video i.video 'medium' %} {% endfor %} This works. All of the videos are arranged one after the other in the webpage. Now I want to display them in a carousal. This is the sample code for the carousal <div id="carouselVideoControls" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselVideoControls" data-slide-to="0" class="active"></li> <li data-target="#carouselVideoControls" data-slide-to="1"></li> <li data-target="#carouselVideoControls" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% for i in videos %} <div class="carousel-item active"> {% video i.video 'medium' %} </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselVideoControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselVideoControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> This is not working. Only the first video is displayed. And when I click the next button nothing happens. Not sure what I am doing wrong here. FYI, The default carousal from bootstrap works. Checked that out with a couple of images. -
Having issues loading django admin static files
Im having issues loading the static files for django admin using the latest django. Now i have tried multiple methods and really would appreciate help. For info im using pythonanywhere for deployment. This is the settings.py file """ Django settings for MyDjangoApp project. Generated by 'django-admin startproject' using Django 2.2.15. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import server_keys as sk # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = sk.django_key # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['192.168.1.22','localhost','username.pythonanywhere.com ','username.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'regs', ] 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 = 'MyDjangoApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['regs/templates/regs'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MyDjangoApp.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } … -
How to split a form field to display multiple values in Django
My Journey model contains two fields, distance and time: class Journey(models.Model): distance = models.PositiveIntegerField(default=0) time = models.PositiveIntegerField(default=0) I am trying to create a Modelform where the time field will be split to display inputs for 'hrs', 'min' and 'sec'. I would then like these values to be compressed in order to return one single value. Currently my forms.py looks like this: from django import forms from django.forms import MultiWidget from .models import Journey class DistanceTimeModelForm(forms.ModelForm): time = forms.MultiValueField(widget=MultiWidget(widgets=[forms.IntegerField(attrs={'placeholder': 'hrs'}), forms.IntegerField(attrs={'placeholder': 'min'}), forms.IntegerField(attrs={'placeholder': 'sec'})]), require_all_fields=True, error_messages={'incomplete': 'Please enter a number'}) class Meta: model = Journey fields = ['distance', 'time'] I am receiving TypeError: __init__() got an unexpected keyword argument 'attrs' when I attempt to run the server. Is anyone able to help me understand how to fix this? I have been searching for a solution online for some time but so far am still stumped. -
getting issue when trying to build docker image on aws on ubuntu 18.04
I am trying to build a docker image on AWS for Defect-Dojo using the below method I have cloned the defect dojo repo from github and trying to build the docker image using this git clone https://github.com/DefectDojo/django-DefectDojo cd django-DefectDojo # building sudo docker-compose build when I run sudo docker-compose build, it throws the following error. I am unable to get the reason. any help please. I am a newbie to docker. thanks here is the output. <pre>mysql uses an image, skipping initializer uses an image, skipping rabbitmq uses an image, skipping celeryworker uses an image, skipping celerybeat uses an image, skipping Building uwsgi Step 1/23 : FROM python:3.5.7-buster@sha256:4598d4365bb7a8628ba840f87406323e699c4da01ae6f926ff33787c63230779 as build ---&gt; 4ae385ba9dd2 Step 2/23 : WORKDIR /app ---&gt; Using cache ---&gt; 4cebcde37520 Step 3/23 : RUN apt-get -y update &amp;&amp; apt-get -y install dnsutils default-mysql-client postgresql-client xmlsec1 git &amp;&amp; apt-get clean &amp;&amp; rm -rf /var/lib/apt/lists &amp;&amp; true ---&gt; Using cache ---&gt; 9fee66bc8f58 Step 4/23 : COPY requirements.txt ./ ---&gt; Using cache ---&gt; b30515f1dfcc Step 5/23 : RUN pip3 wheel --wheel-dir=/tmp/wheels -r ./requirements.txt ---&gt; Using cache ---&gt; 6c5e964ee4ac Step 6/23 : FROM python:3.5.7-slim-buster@sha256:127fee645393d311c7fbc5e8c2e5034f10a4e66b47c9273d4dbe5da2926fc3f2 ---&gt; 5b0283c5034b Step 7/23 : WORKDIR /app ---&gt; Using cache ---&gt; fc28b1a681b0 Step 8/23 : RUN apt-get -y … -
Set currently logged in user as the user in the model when creating an object in Django
I've tried to implement the solutions offered by some of the other posts I see on here, but nothing seems to be working. I'm brand new to django and backend in general, so I may just be lacking in skill. The situation is that I'm letting users generate a listing based on a django model Listings using a ModelForm. Everything seems to be working except for the fact that I can't set the currently logged in user as the user for the listing. I understand that the user is stored in request.user, but I can't seem to set it within my form and I consistently get this error: IntegrityError at /create NOT NULL constraint failed: auctions_listings.listing_user_id Here's the code for my User and Listings model: class User(AbstractUser): pass class Listings(models.Model): title = models.CharField(max_length=64, default="") description = models.TextField(default="") image = models.URLField(blank=True, null=True) initial_bid = models.DecimalField(max_digits=8, decimal_places=2) category = models.CharField(max_length=64, default="Misc") listing_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listing_user") # listing.bid.all()???? and here is my form: from .models import Listings class ListingsForm(forms.ModelForm): class Meta: model = Listings exclude = ('listing_user') fields = [ 'title', 'description', 'image', 'initial_bid', 'category' ] Some of the suggestions I've found have figured out that I can excluse the user requirement … -
I want to make a website like StreamYard, what technology can I use?
I want to make a website like StreamYard, I want my website to have live streaming, screen sharing with the audience, file uploading. I have some experience in Django. Can I use Django to make a website like this? -
How to use the bulk_update with multiple fields?
Here user from the frontend gives the list of values like this ['1','2'] for the model fields so I tried to use the bulk_update but this way neither it is giving me any error nor updating the values of the fields. I tried the similar way for creating with bulk_create and it worked perfectly but with the update it is not working. What I am doing wring here ? models class PVariant(models.Model): name = models.CharField(max_length=255, blank=False, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) sku = models.CharField(max_length=255, blank=True, null=True) ..other fields views names = request.POST.getlist('name') print(names)#['mark','ed'] up = request.POST.getlist('ups') print(up) # ['12','13'] sku = request.POST.getlist('sku') #['1','2'] fields = ['name', 'up', 'sku'..] params = zip(names, up, cp, sku, quantity, weight, v_attributes) #PVariant.objects.filter(product=product).update() variants = [PVariant(name=param[0], up=param[1], sku=param[2],product=product..) for param in params] PVariant.objects.bulk_update(variants, fields) -
Getting NoReverseMatch even though url patterns are correct?
I've been learning Django for like a month so apologies if I'm doing something stupid, but, I'm getting a NoReverseMatch Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<use>[^/]+)$'] error when trying to render a "profile" page under the url '/profile/[a user's name]', and I'm pretty sure all my paths/patterns are correct?? Here's my code, could someone help me with this? All my other url patterns work fine. This path also worked fine before, I just renamed the "user" variable into "use" and this happened. urls.py: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("profile/<str:use>", views.profile, name="profile"), path("following", views.following, name="following"), #api path('', include(router.urls)), ] views.py: def profile(request, use): currentuser = str(request.user) followers = [] following = [] for follow in Follow.objects.filter(following=use): followers.append(follow.person) for item in Follow.objects.filter(person=use): following.append(item.following) follower_count = len(followers) following_count = len(following) try: Follow.objects.get(person=currentuser, following=use) followed = True except: followed = False post_list = Post.objects.filter(user=use) dates = [] for post in post_list: dates.append(post.timestamp) dates.sort(key = lambda date: datetime.strptime(date, '%B %d, %Y, %I:%M %p'), reverse=True) formattedlist = [] for date in dates: postobject = Post.objects.get(timestamp=date) formattedlist.append(postobject) paginatorlist = Paginator(formattedlist, 10) now_page_content = paginatorlist.page(1) nowpage = 1 if request.method == "POST": … -
Django | Redirect on First Login
I have to assume I'm going about this the wrong way... But I'm just learning Django, so I'd like some help. I have a basic blog app. I'd like a user to be taken to the feed regularly after login, but I'd like the user to be taken to their profile on the very first login. Right now, this is in my settings.py: LOGIN_REDIRECT_URL = 'Home' LOGIN_URL = 'login' So, the user is always taken to the feed, 'Home'. I've tried importing the User model to settings and attempted something like this: if not User.last_login: LOGIN_REDIRECT_URL = 'Profile' else: LOGIN_REDIRECT_URL = 'Home' LOGIN_URL = 'login' but as soon as I've imported the User model to the settings.py file, the server will no longer run. I guess that's something I can't do. What's the best approach to achieve the desired outcome? -
Create Log files in Python-Djnago application
i want to create log files in daily basis, want a log file for each day with date in file name and automatic generate log files for each day and automatic rename with date i added a log details in settings.py and tried to add log details . my code is showing below But no log file is creating , no data is writing in the log files. error.log always showing empty and not renaming with date my setting.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} {asctime} {module} {funcName} {lineno:d} {message}', 'style': '{', } }, 'handlers': { 'errors_file': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': os.path.join(BASE_DIR, './log/error.log'), 'when': 'D', 'interval': 1, 'formatter': 'simple', }, }, 'loggers': { 'error_logger': { 'handlers': ['errors_file'], 'level': 'WARNING', }, }, } my view.py try: dev_id = Device.objects.get(DeviceId=input_data["DeviceId"]) return Response({msg: validation["FDP34"]}, status=status.HTTP_200_OK) logging.getLogger("error_logger").exception(validation["FDP34"]) else: return Response({msg: validation["FDP35"]}, status=status.HTTP_400_BAD_REQUEST) logging.getLogger("error_logger").exception(validation["FDP35"]) except Device.DoesNotExist: logging.getLogger("error_logger").exception(validation["FDP8"]) -
My comments are not being displayed in a django blog
I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site. The snippet of my code is below. views.py from .models import Post from django.utils import timezone from .forms import PostForm, CommentsForm from django.contrib.auth.decorators import user_passes_test # Create your views here. def home(request): return render (request, 'blogapp/home.html') def blog_list(request): post = Post.objects.order_by('-published_date') context = { 'posts':post } return render(request, 'blogapp/blog_list.html', context) def blog_detail(request, pk=None): detail = Post.objects.get(pk=pk) context = { 'detail': detail } return render(request, 'blogapp/blog_detail.html', context) def add_post(request, pk=None): if request.method == "POST": form = PostForm(request.POST) if form.is_valid: body = form.save(commit=False) body.published_date = timezone.now() body.save() return redirect('blog_list') form = PostForm() else: form = PostForm() context = { 'form': form } return render(request, 'blogapp/add_post.html', context) def add_comments(request, pk=None): if request.method == "POST": form = CommentsForm(request.POST) if form.is_valid: comment = form.save(commit=False) comment.date_added = timezone.now() comment.save() return redirect('blog_detail') form = CommentsForm() else: form = CommentsForm() context = { 'form': form } return render(request, 'blogapp/add_comments.html', context) urls.py from django.urls import path from . import views urlpatterns … -
how do i provide a Foreign key for two models
let us consider two models Quotes and QuoteUsers. class QuoteUsers(models.Model): created_at = models.DateTimeField(auto_now_add=True) ip_address = models.GenericIPAddressField(blank=True, null=True) class Quote(models.Model): quote_number = models.IntegerField() job_title = models.CharField(max_length=50, blank=True, null=True) reference = models.TextField(blank=True, null=True) quote_type = models.CharField(max_length=45, blank=True) Now here i want to ip_address of each quote and in which model should i apply my ForeignKey and how can i filter the model ? -
Error Message: Internal Server Error Heroku
I keep getting this error when launching my heroku app Internal Server Error then I went to cmd and did this heroku logs --tail and I found out the error was ModuleNotFoundError: No module named 'main.url' my rules from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.url")), ] then I went to settings.py and on my ROOT_URLCONF = 'mysite.urls' I changed instead of mysite.urls I put just urls I still get the same Error message ModuleNotFoundError: No Module named urls my settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'a49c&2is^-d$y8ycdycbenh*@dm3$3phszrs_72c*fh-ti1449' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # remember to change to false ALLOWED_HOSTS = ['anim3-domain.herokuapp.com'] # 'https://anime-domain.herokuapp.com/' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', … -
My Django app doesnt Run again on my local computer Since i changed to Heroku postgrel database
my database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), #'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DatabaseName', } } DATABASE_URL = os.environ['DATABASE_URL'] conn = psycopg2.connect(DATABASE_URL, sslmode='require') import dj_database_url DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True) When ever I try run the server on my computer it shows the error .It happened when i tried changing my database fromsqlite to postgre. the error File "C:\Users\stephen\favprojects\favprojects\settings.py", line 94, in <module> DATABASE_URL = os.environ['DATABASE_URL'] File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'DATABASE_URL' -
why do I get error in Django : unsupported operand type(s) for |: 'Model' and 'Model'
So I have a model named Question. There are three types of objects in Question, and I'm trying to query those objects separately, then merge first objects of each. Like this: def getQuestion(request): typeOne = Question.objects.filter(type=1).order_by('question_number') typeTwo = Question.objects.filter(type=2).order_by('question_number') typeThree = Question.objects.filter(type=3).order_by('question_number') questionsOfTheDay = depthOne[0] | depthTwo[0] | depthThree[0] # I've tried below as well, with chain imported # questionsOfTheDay = chain(depthOne[0], depthTwo[0], depthThree[0]) serialized = QuestionSerializer(questionsOfTheDay, many=True) return Response(serialized.data) I don't see what I've done wrong, but I keep getting the error "unsupported operand type(s) for |: 'Question' and 'Question'". What do you think is the problem? I appreciate it in advance. -
XmlHttpRequest request element is None
I am using Django and trying to send webcam data using XMLHttpRequest to background (view.py) in order to process each frame. I follow this link and most people suggests similar method for my problem. $(document).ready(function(){ $('#trigger_button').click(function(){ navigator.mediaDevices.getUserMedia(constraints) .then(stream => { document.getElementById("myVideo").srcObject = stream; }) .catch(err => { alert('navigator.getUserMedia error: ', err) }); drawCanvas.width = v.videoWidth; drawCanvas.height = v.videoHeight; imageCanvas.width = uploadWidth; imageCanvas.height = uploadWidth * (v.videoHeight / v.videoWidth); drawCtx.lineWidth = 4; drawCtx.strokeStyle = "cyan"; drawCtx.font = "20px Verdana"; drawCtx.fillStyle = "cyan"; imageCanvas.getContext("2d").drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth)); imageCanvas.toBlob(postFile, 'image/jpeg'); }); }); function postFile(file) { var formdata = new FormData(); formdata.append("image", file); formdata.append("threshold", scoreThreshold); var xhr = new XMLHttpRequest(); xhr.open('POST', apiServer, true); xhr.onload = function () { if (this.status === 200) { var objects = JSON.parse(this.response); drawBoxes(objects); imageCtx.drawImage(v, 0, 0, v.videoWidth, v.videoHeight, 0, 0, uploadWidth, uploadWidth * (v.videoHeight / v.videoWidth)); imageCanvas.toBlob(postFile, 'image/jpeg'); } else { alert(this.status); } }; xhr.send(formdata); } Then, I am trying to access data in the request in view.py as follow: def control4(request): print(request.POST.get('image')) print(request.POST.get('threshold')) return render(request, 'local.html') However, although request.Post.get('threshold') returns a value, request.POST.get('image') returns None. Besides, this method repeats three times and then it stops to send feedback. I … -
define you own Meta class options
the following link list all possible metadata options for a Django model: https://docs.djangoproject.com/en/3.1/ref/models/options. Does Django provide a framework to extend the list by defining my own metadata options? e.g., I want to add a custom option secured = True to mask the value of some fields. If so, how? -
Django TypeError 'dict' object is not callable
I get an Error for the line: username = login_form.cleaned_data('username'), because somewhere it seems to be a dict, but I cannot understand why. Can anyone please tell me, what the problem is? views.py def index(request): return render(request, 'web/base.html') def register_view(request): register_form = UserCreationForm() if request.method == "POST": register_form = UserCreationForm(request.POST) if register_form.is_valid(): register_form.save() username = register_form.cleaned_data("username") password = register_form.cleaned_data("password1") user = authenticate(request, username=username, password=password) if user: login(request, user) return render(request, 'web/register.html', {'register_form': register_form}) def login_view(request): login_form = AuthenticationForm() if request.method == 'POST': login_form = AuthenticationForm(data=request.POST) if login_form.is_valid(): username = login_form.cleaned_data('username') password = login_form.cleaned_data('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return render(request, 'web/login.html', {'login_form': login_form}) def logout_view(request): logout(request) return redirect(reverse('web:index')) -
How to select data from oracle table and return into nested json with django rest framework
I have data in oracle as below And I want to return nested json like this I have data in oracle as below Currently I have to create another table for machine code to use foreign key in models.py and serializers.py but I want to know is it possible to select from 1 table and return into nested json? -
how to display the information that related to a specific user
i have this Model class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=200, null=False) state = models.CharField(max_length=200, null=False) zipcode = models.CharField(max_length=200, null=False) date_added = models.DateTimeField(auto_now_add=True) and this view def view_profile(request): data = cartData(request) cartItems = data['cartItems'] shippingAddress = ShippingAddress.objects.all() args = {'user': request.user, 'cartItems': cartItems, 'shippingAddress': shippingAddress} return render(request, 'store/profile.html', args) template {% for sa in shippingAddress %} <p>address: {{ sa.address }}</p> <p>city: {{ sa.city }}</p> <p>state: {{ sa.state }}</p> <p>zipcode: {{ sa.zipcode }}</p> {% endfor %}`enter code here` the problem is the template display all the Shipping Addresses in the DB and i want it just to display the Shipping Address that related to the signed in user Thanks