Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django with docker dosen't see pillow
I'm trying to deploy my project on django. I almost did it but django can't see installed pillow in docker container. I'm sure that it's installed pip sends me this: sudo docker-compose -f docker-compose.prod.yml exec web pip install pillow Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: pillow in /usr/local/lib/python3.8/site-packages (8.1.0) But when i'm trying to migrate db i see this: ERRORS: history_main.Exhibit.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". history_main.MainUser.avatar: (fields.E210) Cannot use ImageField because Pillow is not installed. -
How can I save a flag on Proxy model field?
I know it is probably very basic knowledge, but for some reason looking for basic Django stuff is really painful. I have one main model, which is then used as proxy to create second model. I then change second model in admin.py in order to use less fields than original model, and I wanted to use a flag (either True in Boolean field, or 'y' or whatever) to show that it was created using proxy model without user interaction (so I don't want person to manually click the Boolean field or whatever). So basically, in models.py: class MainModel(models.Model): is_proxy = whatever (can be Boolean, can be Char, whatever works) (...) class ProxyModel(MainModel): class Meta: proxy = True admin.py: class FromProxyModel(admin.ModelAdmin): fieldsets = ( `less fields than original model`,) //here is a function or something I would like to use to save value of is_proxy to True, y or whatever admin.site.register(ProxyModel, FromProxyModel) Could you please help me how can I properly change the value of is_proxy field, to be set only when proxy model was used? -
POST on many to many Django rest framework
models class Customer(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) phone = models.CharField(max_length=11,blank=True,null=True) likecus=models.ManyToManyField(smartphone ,verbose_name="лайк") class smartphone(models.Model): title=models.CharField(max_length=255) Serializer class CreateCustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('phone', 'likecus') I get the error that the required field of A is not sent. This setup works for PUT call however. The issue with PUT call is that when I call the PUT call again, it overrides the existing data in the AB relation field with the new data and not simply appends the data of second API call to the first. How can I POST data so that I am able to link existing B records with A records? through the Primary Key Related Field. I have this created has not changed. I don't know, some people have solved the problem this way. it doesn't work for me -
Converting dynamic website to android applications
I have a dynamic website build on Django. I want to create an apk and with no knowledge on building apks I I found out there are few methods to convert a website to an app in few minutes. I want to know if the functionality of the app remains the same. I want someone to explain me how does it work. Does the database get updated when I update the database using the apk? or if it is even possible to update the database in my server? or does the app remain static?. Being a noob I need your help in this. -
How to access different static files for different Django applications on IIS?
Suppose I have two Django apps: DjangoApp1 and DjangoApp2 I have created a website with DjangoApp1 in IIS with some IP(192.168.1.1) on port 80, and I can access this website on 192.168.1.1/, the static files are loaded by the virtual directory static, and this site is seen perfectly as expected. Now, for the second app, DjangoApp2, I need to access it through the same IP address in this way: 192.168.1.1/app2/, so I created an Application in my website with the name app2 and configured it accordingly. Now, since DjangoApp2 has a different set of static files, I need to configure my server so that it loads those files as well. Since I already have a virtual directory named static, I can't create one with the same name. I tried creating app2_static and all other combinations, but these files were not loading. All the other functionalities of this app work correctly, which are not dependent on the local static files. How do I configure the StaticFileModule so that it loads the necessary files for DjangoApp2, without disturbing the files of DjangoApp1? I have used FastCgi and wfastcgi module of Django for the deployment configurations. -
Can Django Template language replace JavaScript in a beginner project? [closed]
I am a beginner programmer and I am currently making a web project which involves booking equipment and storing/ retrieving it from the inventory. Basic website, about 5-7ish webpages and around 4-5 tables in the database of the app. I have decided to use django for the same. I had some confusion, do I HAVE to use any JavaScript at all for developing this web project? Can i make it entirely using Django - and HTML/CSS obviously? I have around 25 days to complete this and have currently made some very simple HTML/CSS pages and implemented some django template language in them, like 'extends', forms, etc. Any help is greatly appreciated! Thank You. Pranay -
how to fetch data from ManyToManyFIeld
I am trying to fetch data from ManyToMany Field Here is model : class Product(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=200) product_main_image = models.ImageField(upload_to="images/", null=True, blank=True) product_other_images = models.ManyToManyField(ProductImages, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) price = models.IntegerField(null=True, default=0) discount_price = models.IntegerField(null=True, blank=True, default=0) discount_percentage = models.IntegerField(null=True, blank=True, default=0) size = models.ManyToManyField(ProductSizes, blank=True) # height = models.IntegerField(null=True, blank=True) # weight = models.IntegerField(null=True, blank=True) # length = models.IntegerField(null=True, blank=True) color = models.ManyToManyField(ProductColors, blank=True) spec = models.ManyToManyField(ProductSpces, blank=True) uoms = models.ManyToManyField(UOM) stock = models.BooleanField() SKU = models.CharField(max_length=150) currency = models.ForeignKey(Currency, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.name Here is my product model where there is a object called uoms.Which is ManyToField. Here is my UOM model: class UOM(models.Model): title = models.CharField(max_length=100) height = models.DecimalField(null=True, default=0, max_digits=10, decimal_places=2) width = models.DecimalField(null=True, default=0, max_digits=10, decimal_places=2) weight = models.DecimalField(null=True, default=0, max_digits=10, decimal_places=2) length = models.DecimalField(null=True, default=0, max_digits=10, decimal_places=2) quantity = models.IntegerField(null=True, default=1) def __str__(self): return self.title From this UOM model i took manytomanyfield. So now, i have a page where all the options showed in a drop down. but when a customer will choose one of the uoms it will pass with the cart. Here is a sample … -
Can't access nested dictionary data **kwargs python and best practices for nested data mutation in GraphQL
In Graphene-Django and GraphQL I am trying to create a resolve_or_create method for nested data creation inside my mutations. I'm trying to pass a dictionary with the input from the user as a **kwarg to my resolve_or_create function, and though I can see "location" in the variable watcher (in VSCode), I continuously am getting the error 'dict' object has no attribute 'location' Here's my resolve_or_create method: def resolve_or_create(*args, **kwargs): input = {} result = {} input.location = kwargs.get('location', None) if input.location is not None: input.location = Location.objects.filter(pk=input.location.id).first() if input.location is None: location = Location.objects.create( location_city = input.location.location_city, location_state = input.location.location_state, location_sales_tax_rate = input.location.location_sales_tax_rate ) if location is None: return None result.location = location and my CreateCustomer definition, where this method is being called class CreateCustomer(graphene.Mutation): class Arguments: input = CustomerInput(required=True) ok = graphene.Boolean() customer = graphene.Field(CustomerType) @staticmethod def mutate(root, info, input=None): ok = True resolved = resolve_or_create(**{'location':input.customer_city}) customer_instance = Customer( customer_name = input.customer_name, customer_address = input.customer_address, customer_city = resolved.location, customer_state = input.customer_state, customer_zip = input.customer_zip, customer_email = input.customer_email, customer_cell_phone = input.customer_cell_phone, customer_home_phone = input.customer_home_phone, referred_from = input.referred_from ) customer_instance.save() return CreateCustomer(ok=ok, customer=customer_instance) Here is an example mutation that would create a new customer with an existing location mutation createCustomer { … -
Django PWA navbar is only hidden on the first page ios
I'm using a Django Project as PWA and the navbar is only hidden at the first page. At the moment an href is used the navbar gets visible. Is there any were to fix it ? -
Search for partial match and case insensitive in django_filters
In my filters.py I have a filter: class myFilter(django_filters.FilterSet): class Meta: model= bdMuebles fields = ["Type","Code","Name"] and in views.py I have: def vwMuebles(request): vrMuebles=bdMuebles.objects.all() vrFiltroMbl=myFilter(request.GET,queryset=vrMuebles) vrMuebles=vrFiltroMbl.qs return render(request,"MyApp/Muebles.html",{ "dtMuebles":vrMuebles, "dtFiltroMbl": vrFiltroMbl, }) My question is: How can myfilter search for partial matches with case insensitive, ie, if type app it gives MyApp Application Apple -
Django Nested Serializer Field - Empty OrderedDict
I'm currently having an issue with updating a nested serializer field, the dict value provided is being thrown away and mapped to an empty dict on the code side Serializer: class OrganizationSerializer(QueryFieldsMixin, BaseSecuritySerializer): class Meta: model = Organization fields = ("id", "name") depth = 0 class UsersSerializer(QueryFieldsMixin, BaseSecuritySerializer): organizations = OrgsSerializer(many=True) class Meta: model = Users fields = '__all__' depth = 0 def update(self, instance: ReportSchedule, validated_data): print("validated_data:", validated_data) ... REST Request: METHOD: Patch { "organizations": [{"id": 10}] } Outcome of print statement validated_data: {'organizations': [OrderedDict()]} -
Django FOREIGN KEY constraint failure in pre_delete
I've read quite a few related questions, since this is a beginner DB mistake, but for some reason I can't apply the answers to my situation. I have the following Event model, which contains a foreign key to a Machine model describing the originator of an event, class Event(models.Model): machine = models.ForeignKey( Machine, on_delete=models.SET_NULL, null=True, help_text='The machine this event originated from, or NULL if it has been deleted.') CATEGORY_MACHINE_CREATED = 'machine-created' CATEGORY_MACHINE_UPDATED = 'machine-updated' CATEGORY_MACHINE_REMOVED = 'machine-removed' CATEGORY_CHOICES = ( (CATEGORY_MACHINE_CREATED, 'Machine has been created'), (CATEGORY_MACHINE_UPDATED, 'Machine has been updated'), (CATEGORY_MACHINE_REMOVED, 'Machine has been removed'), ) category = models.CharField( max_length=25, choices=CATEGORY_CHOICES, help_text='The category of the event.') date = models.DateTimeField( default=timezone.now, help_text='The time this event was created.') def __str__(self): return f"<Event id={self.id} machine={self.machine} category={self.category}>" class Meta: ordering = ['-date'] I use signals to generate events around the lifetime of Machine models, @receiver(post_save, sender=Machine) def machine_change_callback(sender, instance, created, **kwargs): if created: logger.warning("CREATED %s %s %s" % (sender, instance, kwargs)) return Event.objects.create( category=Event.CATEGORY_MACHINE_CREATED, machine=instance) else: logger.warning("UPDATED %s %s %s" % (sender, instance, kwargs)) return Event.objects.create( category=Event.CATEGORY_MACHINE_UPDATED, machine=instance) @receiver(pre_delete, sender=Machine) def machine_deleted_callback(sender, instance, **kwargs): logger.warning("REMOVED %s %s %s" % (sender, instance, kwargs)) return Event.objects.create( category=Event.CATEGORY_MACHINE_REMOVED, machine=instance) Then, the following works as I expect, from … -
Capture DEBUG, INFO log level messages in Heroku
I would like to see INFO and DEBUG level logs in Heroku but I'm no sure how. Papertrail, for example, only shows WARNING level logs and above and I don't see any option to change that. I'm using python-django, but I don't think that matters. Is there any option to capture all logs in Heroku? -
Django dynamic form for variations products
I have two models for creating dynamic variations for each product, 'ItemVariation' --> e.g. Blue, Yellow, ... and 'Variation' --> e.g. Color, Size,... class Variation(models.Model): product = models.ForeignKey( Product, related_name='variations', on_delete=models.CASCADE) name = models.CharField(max_length=50) class Meta: unique_together = ( ('product', 'name') ) def __str__(self): return self.name class ItemVariation(models.Model): variation = models.ForeignKey( Variation, related_name='item_variations', on_delete=models.CASCADE) value = models.CharField(max_length=50) image = models.ImageField(blank=True) class Meta: unique_together = ( ('variation', 'value') ) def __str__(self): return self.value As you can see the variations are dynamic, and I can't figure how to add them to a form and then into view -
Django - Only allow one session per user results in Bad request
for some reason I get back http 400 (Bad Request) if I login on another browser while refrshing the first. I just want to accomplish that one user can only have one active session at a time. models.py class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) signals.py @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions old_sessions = Session.objects.filter(usersession__user=user) if request.session.session_key: old_sessions = old_sessions.exclude(session_key=request.session.session_key) old_sessions.delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) For some reson the first browser does not delete the session, instead it keeps the session and I get back http 400 until I delete the session key manually. I would expect that If the session key does not exist anymore the user is redirected to the login. Can smb. Help? Kind regards -
Reverse for 'xyz' not found. 'chat' is not a valid view function or pattern name. At redirect('xyz')
I am getting an error while using the path in Django. this is the code where the redirect function is called in views.py def addmsg(request): c = request.POST['content'] new_item = messageItem(content = c) new_item.save() bot_msg(c) return redirect('chatapp:chat') urls.py app_name = 'chatapp' urlpatterns = [ path('chat', views.chatbot, name='chat'), path('addmsg',views.addmsg, name='addmsg'), ] Django error: NoReverseMatch at /addmsg Reverse for 'chat' not found. 'chat' is not a valid view function or pattern name. Request Method: POST Request URL: http://localhost:8000/addmsg Django Version: 2.2.17 Exception Type: NoReverseMatch Exception Value: Reverse for 'chat' not found. 'chat' is not a valid view function or pattern name. Exception Location: C:\Users\xyz\Documents\Python\hotel\hotel2\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: C:\Users\xyz\Documents\Python\hotel\hotel2\env\Scripts\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\xyz\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2\\env', 'C:\\Users\\xyz\\Documents\\Python\\hotel\\hotel2\\env\\lib\\site-packages'] Server time: Mon, 1 Feb 2021 18:26:38 +0000 I have also registered the app name in settings.py -
i need help beacause django with doesnt really work for me
Im having a problem with project for school that im working on. when i run the code and go to "random page" link that i created, nothing happens. After trying for a bit, i think the problem is that whatever is in {{}} doesnt seem to be found. views.py: from django.shortcuts import render from django.http import HttpResponse from . import util import random def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) random_page = random.choice(entries) def CSS(request): return render(request, "encyclopedia/css_tem.html", { "article_css": "css is slug and cat" }) def Python(request): return render(request, "encyclopedia/python_tem.html", { "article_python": "python says repost if scav" }) def HTML(request): return render(request, "encyclopedia/HTML_tem.html", { "article_HTML": "game theory: scavs are future humans" }) def Git(request): return render(request, "encyclopedia/Git_tem.html", { "article_Git": "github is git" }) def Django(request): return render(request, "encyclopedia/Django_tem.html", { "article_Django": "this is a framework" }) layout.html: <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> Create New Page </div> <div> <a href = "http://127.0.0.1:8000/{{random_page}}">Random Page</a> </div> {% block nav … -
Django: Not able to execute Validators instead the Except block execute
I'm trying to make an email and password validation using validators in Django. I have my own custom Registration form. I'm just fetching the email and password values from it using a view called 'Register'. Whenever I try to register a new user, the code always runs into the except block, I'm pretty sure I'm doing something wrong with validate_email() and validate_password(). Here's my view: def register(request): if request.method == 'GET': return render(request, 'index.html') else: username = request.POST['username'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] try: validate_email(email) except ValidationError: return render(request, 'register.html', {'emailErr':'Hmm.. Did you enter a valid email?'}) try: validate_password(pass1) validate_password(pass2) except ValidationError: #This block runs return render(request, 'register.html', {'passErr':'Please enter a valid password'}) if User.objects.filter(email=email).exists(): return render(request, 'register.html', {'error1':'Email already exists'}) else: if pass1 == pass2: try: user = User.objects.create_user(username=username, password=pass1, email=email) user.save() login(request,user) sendConfirm(user) return render(request, 'confirm_please.html') except IntegrityError: return render(request, 'register.html', {'error2':'User already exists'}) else: return render(request, 'register.html', {'error3':'Make sure the passwords are same'}) A little help would be appreciated -
Validating views.py
Can someone advice me how to prevent to 'POST' empty form? i think im missing: if form.is_valid()... but im too noob and dont know where to implement it... def addContact(request): if request.method == 'POST': new_contact = Contact( full_name = request.POST ['fullname'], relationship = request.POST ['relationship'], email = request.POST ['email'], phone_number = request.POST ['phone-number'], address = request.POST ['address'], ) new_contact.save() return redirect('/contact') return render(request, 'contact/new.html') -
How to add Django env folder into .gitignore?
What would I write in my .gitignore file to make it so the CIS440_Env folder is ignored? -
Why am I getting the "refers to field which is not local to model" error while migrating the following models?
I am trying to create a database schema for a simple Visitor Management System where I am creating two models named Visitor and Host by extending the inbuilt User model in Django. The model Appointment is for mapping the relation between the Visitor and Host with their meeting time slot. However, I am getting the 'demoapp.Appointment.host_email' refers to field 'email' which is not local to model 'demoapp.Host' error mentioned in the title when I run python manage.py makemigrations. Why am I getting this, how can I fix it and is there a better way to do it? from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.core.validators import RegexValidator class Host(User): class Meta: verbose_name = "Host" verbose_name_plural = "Hosts" phone = models.CharField(verbose_name='Phone Number',max_length=10, validators=[RegexValidator(regex='[0-9]{10}')], unique=True, null=True) class Visitor(User): class Meta: verbose_name = "Visitor" verbose_name_plural = "Visitors" phone = models.CharField(verbose_name='Phone Number',max_length=10, validators=[RegexValidator(regex='[0-9]{10}')], unique=True, null=True) purpose = models.CharField(verbose_name='Purpose of meeting', max_length=150, null=True) class Appointment(models.Model): host_email = models.ForeignKey(Host, to_field='email', on_delete=models.CASCADE, verbose_name='Host Email') visitor_email = models.ForeignKey(Visitor, to_field='email', on_delete=models.CASCADE, verbose_name='Visitor Email') slot = models.DateField(verbose_name='Appointment Slot', default=timezone.now) is_confirmed = models.BooleanField(verbose_name='Booking Confirmed', default=False) -
unable to load CSS of Static files in django
i just created a django app in project. when i am running the server content is displaying but css styles are not applying. Here is my settings configuration of staticfiles. STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') urls configuration of staticfiles. if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) here is code of html : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>MyApp</title> <link rel="stylesheet" href="{% static 'css/app.css' %}"> </head> -
How can I make my User fields case insensitive during user-login?
I'd like to make my user login fields non case-sensitive for username and email only. I applied it to my models, but then I realized I should keep the data as is and true to itself. How can I apply case-insensitivity to the two fields mentioned above? views.py class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request, format='json'): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() if user: json = serializer.data return Response(json, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) username = serializers.CharField(required=True) password = serializers.CharField(min_length=8, write_only=True) first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) subscribed = serializers.BooleanField(default=False) class Meta: model = User fields = ('email', 'username', 'password','first_name','last_name','subscribed') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance model.py: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) start_date = models.DateTimeField(default=timezone.now) subscribed = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name','password'] def __str__(self): return self.username Thank you for any guidance! -
How to get Web Socket to receive messages with Django Channels
I have a chat application with React handling the frontend and Django with using Channels to handle the web socket connection. I can see both on the frontend and backend that the socket is connected and I can see in the terminal that the receive function in ChatConsumer runs but the client isn't receiving it and I can not figure out why. Also if I run self.send() on the connect function in the ChatConsumer, then the client then receives the message. Any help would be greatly appreciated. Here is my code -> asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import rooms.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'musicapp.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( rooms.routing.websocket_urlpatterns ) ) }) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/room/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] consumers.py import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): # Do nothing on disconnect pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) print('[SOCKET] Transmitting a message: ', text_data) room.js import React, { useState, useEffect } from "react"; import axios from 'axios'; import Cookies from 'js-cookie'; import { makeStyles } … -
How to copy a object data to another object in Django?
I am trying to create an E-Commerce Website and I am at the Final Step i.e. Placing the Order. So, I am trying to add all the Cart Items into my Shipment model. But I am getting this error. 'QuerySet' object has no attribute 'product' Here are my models class Product(models.Model): productId = models.AutoField(primary_key=True) productName = models.CharField(max_length=200) productDescription = models.CharField(max_length=500) productRealPrice = models.IntegerField() productDiscountedPrice = models.IntegerField() productImage = models.ImageField() productInformation = RichTextField() productTotalQty = models.IntegerField() alias = models.CharField(max_length=200) url = models.CharField(max_length=200, blank=True, null=True) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) email = models.EmailField(max_length=100) profileImage = models.ImageField(blank=True, null=True, default='profile.png') phoneNumber = models.CharField(max_length=10, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) dateOrdered = models.DateTimeField(auto_now_add=True) orderCompleted = models.BooleanField(default=False) transactionId = models.AutoField(primary_key=True) class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, blank=True, null=True) dateAdded = models.DateTimeField(auto_now_add=True) class Shipment(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) orderId = models.CharField(max_length=100) products = models.ManyToManyField(Product) orderDate = models.CharField(max_length=100) address = models.CharField(max_length=200) phoneNumber = models.CharField(max_length=13) I just removed additional functions i.e. __str__ and others. Here is the views.py def orderSuccessful(request): number = Customer.objects.filter(user=request.user).values('phoneNumber') fullAddress = Customer.objects.filter(user=request.user).values('address') timeIn = time.time() * 1000 …