Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrating to Django 2.2 from 1.11 -- old migrations without on_delete in ForeignKey break everything
I'm working on upgrading my legacy application from Django 1.11.13 to 2.2.8. I've dutifully addressed every compatibility issue, but I've hit one I can't figure out how to resolve. When I try to start the webserver in my local environment, I get this error (only showing the end of the full error trace that appears): File "/Users/me/my_app/my_model/migrations/0001_initial.py", line 37, in Migration ('entry', models.ForeignKey(to='my_model.Entry')), TypeError: __init__() missing 1 required positional argument: 'on_delete' I understand why on_delete is now required -- I just spent a while updating my models everywhere to accommodate this change -- but I have no idea how to fix this particular issue without going through dozens of old migrations files to make them conform?! I tried squashmigrations to at least collapse the number of places I have to clean up, but I got the same exact TypeError. I tried to use the old version of Django for squashmigrations. I was successful in avoiding the TypeError, but ended up with a huge mess of circular import errors. Since I don't actually need the migration history to roll back, I tried to follow these instructions (scenario 2) to clear the migration history while keeping the existing database, but I couldn't … -
Can I post the javascript array to the database in django framework?
I am new to django, I am having an users table and designs table as given below class designs(models.Model): id=models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') > class users(models.Model): email = models.CharField(max_length=50,default='0000000') password = models.CharField(max_length=50,default='0000000') design = models.ManyToManyField(designs) The user will click the designs he want it is a multi select and after clicking every the every design i wrote a javascript array to store the details of every design clicked by the user like this styles=[2, "../static/images/2.jpg", "Rustic & Warm", 3, "../static/images/3.jpg",…] So,in the form I took hidden input of design_id like this <form action="{% url 'car:user_register' %}" method="POST"> > {% csrf_token %} > <div class="form-group"> > <label for="design_id"></label> > <input type="hidden" name="design_id" class="form-control" value="styles"required> > </div> > > And my views.py def user_register(request): if request.method == 'POST': design_id=request.POST.GET('styles[]') email = request.POST['email'] password = request.POST['password'] user = users(password=password,email=email,design_id=design_id) user.save() return render(request,'home.html') Is that a correct way of getting and posting that javascript array in the database -
How to populate initial values of form from queryset
I have a FormView with a get_initial method which I am trying to use to populate the form. I am trying to get the EmployeeTypes of the receiver of the memo as values in the form. def get_initial(self): initial = super(NotificationView, self).get_initial() users = Memo.objects.filter(id=self.kwargs['pk']).values('receiver__employee_type') initial['receiving_groups'] = users return initial There are 2 issues here.. This returns a Queryset which looks like: <QuerySet [{'receiver__employee_type': 'Bartender'}, {'receiver__employee_type': 'Supervisor'}]> when I really need the fields in the form to be the EmployeeType itself. Most importantly - the form isn't even rendering these fields. Here is the form just in case: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) How do I populate the fields of the form? -
Error while updating mongodatabase collections from django app using djongo
I am facing an error. I am trying out the polls tutorial as provided in the django documentation. The problem is with the django 'F' function. I am trying to update the number of votes for a choice. If I load the choice object into python memory and do the normal numeric addition it is working. But if I use choice.update(votes=F('votes')+1) then it is giving me the following error. djongo.sql2mongo.SQLDecodeError: FAILED SQL: UPDATE "poll_choice" SET "question_id" = %(0)s, "choice_text" = %(1)s, "votes" = ("poll_choice"."votes" + %(2)s) WHERE "poll_choice"."id" = %(3)s Params: (1, 'huntress', 1, 3) If we observe %(2)s is supposed to be a number and not a string. But it is going as a string. Please help how I can resolve this . I am using djongo 1.2.38 with sqlparse version 0.2.4. -
Django Model seeking alternative to many to many fields
I am writing an exam system, below is my model: class Exam(models.Model): name = models.CharField( max_length=100 ) class Topic(models.Model): name = models.CharField( max_length=50 ) class Question(models.Model): title = models.CharField( max_length=100 ) topic = models.ForeignKey( Topic ) class Choice(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE ) choice_text = models.CharField( max_length=200 ) is_right_answer = models.BooleanField( default=False ) I want when I create an exam, i can give multiple topics like math, physics, business etc and then i can query all the questions related that topics and show in the frontend. My problem only in exam creation, i am not getting should I use ManyToManyField or there is any alternative solution I just want to select multiple topic during i create an exam. Can anyone help me in this case? -
Why is my Django form is not displaying anything?
I am following a tutorial in which we will create a form to hold simple object parameters. Here's the code: forms.py from django.forms import ModelForm from .models import Item class ItemForm(ModelForm): class Meta: model = Item fields = ['item_name', 'item_desc', 'item_price', 'item_image'] models.py from django.db import models class Item(models.Model): def __str__(self): return self.item_name item_name = models.CharField(max_length = 200) item_desc = models.CharField(max_length= 200) item_price = models.IntegerField() item_image = models.CharField(max_length=500, default ="https://i.jamesvillas.co.uk/images/jvh/holiday-destinations/resort/food-placeholder.jpg" ) urls.py from . import views from django.urls import path urlpatterns = [ path('', views.index, name = 'index'), path('item/', views.item, name = 'item'), path('info/', views.info, name = "info"), path('<int:item_id>/', views.detail, name = "detail" ), #add form path('add', views.create_item, name = "create"), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item from django.template import loader from .forms import ItemForm #Some code here def create_item(request): form = ItemForm(request.POST or None) if (form.is_valid()): form.save() return redirect('food/index') return render(request, 'food/item-form.html', {'form': form}) food/item-form.html <form method = "POST"> {% csrf_token %} {{ form }} <button type= "Submit" >Save</button> </form> Now when I go to http://localhost:8000/food/add, it displays an empty page! I have followed the tutorial the exact same way then why is My project not working? -
Join and format array of objects in Python
I want to join and format values and array of objects to a string in python. Is there any way for me to do that? url = "https://google.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" } ] url = "https://google.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "Chennai Express", "rating": "5.0" } ] url = "https://bing.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "1.5" }, { "restaurant": "Bangkok Palace", "rating": "4.5" } ] url = "https://bing.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "4.5" }, { "restaurant": "Chennai Express", "rating": "3.0" } ] I want to be able to format the values as such: If I could make it look like: all_data = [{ url = "https://google.com", results = [{ search = "thai food", search_res = [{ "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" }] }, { search = "Indian food", search_res = [{ "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "CHennai Express", "rating": "5.0" }] }] }, { url = "https://bing.com", … -
Webhost Platform for PostGIS, Django and Celery
I'm currently developing a django web app. I'm trying to decide which platform is best suited to host it. I was considering PythonAnywhere but it seems like they don't support celery or other long running processes. Any suggestions? -
How to initialize form with some parameters of model instance
I would like be able to send SMS/Email notifications manually using the groups/users of a model instance. Let's say the model looks like this: class Memo(models.Model): title = models.CharField(max_length=100) receiver = models.ManyToManyField(EmployeeType, related_name='memos_receiver') I pass the object instance to the view: path('<int:pk>/notify', NotificationView.as_view(), name='memos-notify'), The form and the view are where I am having trouble. I figure I should be able to just pass the forms initial fields right there in the view: class NotificationView(FormView): template_name = 'memos/notification_form.html' form_class = MemoNotificationForm success_url = reverse_lazy('overview') def get_initial(self): initial = super(NotificationView, self).get_initial() memo = Memo.objects.filter(id=id) initial['receiving_groups'] = memo.receiver return initial And the form looks like this: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Do I need to initialize the queryset in the form? Would appreciate it if someone could paint me a clear picture of the why and how here. Thank you! -
Crispy Django Form With RadioBox - Using InlineRadios
I want to style in Radio button in Django using Crispy Form. However, I have successful making use of CSS which is applied to the form but I need to display the form n inline format. After rendering the form in my html, I got a put which is not in inline format. I will be very happy if I can more detail about crispy form using radio button or selected button class ViewForm(forms.Form): #django gives a number of predefined fields #CharField and EmailField are only two of them #go through the official docs for more field details VIEWS = ( ('1', 'Likes & Comments'), ('2', 'Subscribers'), ('2', 'App Installs'), ) GENDER = ( ('1', 'Female'), ('2', 'Male') ) AGE = ( ('All', 'All'), ('13 - 24', '13 - 24'), ('25 - 34', '25 - 34'), ('35 - 44', '35 - 44'), ('45 - 54', '45 - 54'), ('55 - 64', '55 - 64'), ) CATEGORY = ( ('Auto', 'Auto'), ('Beauty', 'Beauty'), ('Sport', 'Sport'), ) CHOICES=[('select1','select 1'), ('select2','select 2')] view= forms.ChoiceField(label='BESIDE VIEWS, I ALSO WANT:', widget=forms.RadioSelect, choices=VIEWS) age= forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=AGE) gender = forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=GENDER) location = forms.CharField(max_length=25, required=False) category= forms.CharField(label='CATEGORY', widget=forms.Select(choices=CATEGORY)) keyword = forms.CharField(max_length=50, required=False) my css input[type=radio], … -
Django TestCase object has no attribute 'login'
I have used selenium to test my login method and it works fine. Then, I tried to test other parts of the website. So, I needed to create a user in my test. To do that, I've used client instead of request factory (since there are middleware classes). However, I am getting the error: AttributeError: 'ProjectListTestCase' object has no attribute 'login' I do have a custom authentication backend to allow for email address to be used instead of username: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'rest_framework', # 3rd party apps 'crispy_forms', # Local apps 'accounts', ... I tried the code in the console: >>> the_client = Client() >>> the_client.login(email='test@testing.com', password='testingPassword') True Here is the code in my test_views.py: from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.test import TestCase from django.test import RequestFactory from model_mommy import mommy from selenium import webdriver from project_profile.models import Project from user_profile.models import UserProfile class ProjectListTestCase(TestCase): def setUp(self): # login the user login = self.client.login(email='test@testing.com', password='testingPassword') print ('Login successful? ', self.login) # Just to see what's going on response = self.client.get(reverse('development:list_view_developmentproject') ) print('response: ', self.response) # Just to see what's going on def test_user_login(self): self.assertEqual(self.response.status_code, 200) Why do I … -
Send mail inside action django-rest-framework
i'm learning django restframework by myself I'm trying to send a mail with sengrid inside an action enter image description here The mail doesn't send Sorry for menglish thank you -
Django background task repeating more than it should
I am trying to run a django background task every 30 seconds, as a test I'm having it print "hello", but instead of printing every 30 seconds it is printing about every second or less very quickly. Here is my code currently: from background_task import background from datetime import timedelta, datetime @background(schedule=datetime.now()) def subscription_job(): print("hello") subscription_job(repeat=30) -
How to make the user visible to al his group activities
I am doing a django-rest-framework project in which one can create groups by adding member’s email id and the logged in user should be able to see all the group activities. I used django-multi-email-field to store the list of emails of respective members Now the user can see his own activities when logged in.How can i make the user visible to all the group activities.Should i create a model inside a model? Please help me. -
Failed lookup for key in templates
I am trying to get Specific List in Dictionary, but first i got the error: "fail to lookup for key", searching on internet I found out a tread with this solution: {% with obj1.page.val2 as val2 %} {{ obj1.val1|default:val2 }} {% endwith %} But It does not work any help here is my code: keyData = '\'' + id + '|' + id2 + '|' + id3 + '\''; console.log(keyData); var val2; try { {% with keyData as val2 %} console.log(val2); datas = {{product_prices_complex_key|get_item:val2|safe}}; {% endwith %} console.log(datas); }catch(err){console.log(err);} KeyData: WA5-8|2|5 And is in the dictionary. Thanks in Advanced -
Django model method error: missing 1 required positional argument: 'self'
I want to do some calculations inside a model and between attributes. I want 3 fields that can be entered by the user to add the model, but those fields get concatenated into a non-editable field that can be used for viewing purposes only. Here is the model I have: class Dossier(models.Model): #Dossiers sinistre numero = models.CharField(max_length=20, default=dossier_number, editable=False) created_by = models.ForeignKey(Prestataire, on_delete=models.SET_NULL, null=True) mat_id = models.CharField(max_length=7, default="123456") mattypes = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ) mat_symbol = models.CharField(max_length=3, choices=mattypes, default="A") mat_ville = models.CharField(max_length=2, blank = True) def define_matricule(self): if self.mat_symbol == "A" or "B": return str(self.mat_id) + '-' + str(self.mat_symbol) + '-' + str(self.mat_ville) else: return str(self.mat_id) + '-' + str(self.mat_symbol) matricule = models.CharField(max_length=20, default=define_matricule, editable=False) But when I run this, I find this error: Django Version: 2.2.5 Exception Type: TypeError Exception Value: define_matricule() missing 1 required positional argument: 'self' Exception Location: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py in get_default, line 797 Python Executable: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\python.exe Here's my traceback: Environment: Request Method: GET Request URL: http://localhost:8000/dossiers/nouveau Django Version: 2.2.5 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'formtools', 'dashboard.apps.DashboardConfig', 'crispy_forms', 'photologue', 'sortedm2m'] Installed 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'] Traceback: File "C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" … -
get_decoded method show "Session data corrupted" in Django session
I have an application which using Django 2.0 and I'm facing with an issue about session data today. (SECRET_KEY is a static string, and consistent among the app so this might not is the issue) The command I've tried is: from django.contrib.sessions.models import Session session = Session.objects.first() session.get_decoded() # Session data corrupted # {} Even when I clear all the sessions, login again for a new session but still facing the same issue. I really want to read the session from the backend using manage.py shell and those script above. -
How to return user session id alongside Django rest serializer output
I'm writing a web application with Django. In one of my APIs which is using Django rest_framework, I want to return user's session ID alongside the default response. I know how to get the session ID but I don't know how to put it alongside the response(for example, in a JSON format) This is my code: class HouseInfoSerializer(serializers.ModelSerializer): class Meta: model = House fields = '__all__' class HouseViewSet(generics.ListAPIView): serializer_class = HouseInfoSerializer def get_queryset(self): postcode = self.kwargs['postcode'] print(self.request.session.session_key, "*"*10) return House.objects.filter(postcode=postcode) -
python - group values when generating a json
I am generating below JSON using a piece of code. Basically, I need to group my generated JSON group by continent, and then country and languages [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us" } ] }, { "region": "ar", "country": "Argentina", "languages": [ { "language": "es-ar" } ] }, { "region": "bo", "country": "Bolivia", "languages": [ { "language": "es" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "en-us" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "pt-br" } ] } ] }} I am generating above JSON using the below code. def get_available_locales_json(): locales = [] for locale in get_available_locales(): append_locale = True for entry in locales: if entry['continent'] == locale.region.continent: entry['regions'].append({'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}) append_locale = False break if append_locale: locales.append( { 'continent': locale.region.continent, 'regions': [{'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}] } ) return locales However, I need to group languages together without having an extra node for the country. something like below, [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us", "language": "es-ar" } … -
How can I convert a duration or a string to an integer in a queryset in Django views.py?
I need to calculate the time difference between two rows. This duration then needs to be adjusted up to 1 if the total is 0, or if the total is over 15 minutes, adjusted to 0--I was going to put this corrected amount in strtime. Unfortunately, my calculated times are not correct nor can I convert the extracted minutes to an integer in order to test if the duration is > 15 or < 1. The only reason I converted to a string was to see if I could then convert to an integer--it didn't work. I also tried to convert to a pandas dataframe in order to do the calculations, but I could not get it back into some format to display properly on the html page. How can I do an accurate calculation between rows and how can I adjust from 0 to 1 or > 15 to 0? I have tried many different versions--just not having much luck. I normally work in javascript--this is my first Django project. I have sanitized and shortened the data. This page will fit into an existing Django setup. Thank you in advance! Code is below. models.py class testmodels(models.Model): primary_key_id = models.CharField(max_length=150, … -
Django queryset caching with exists()
Let's say, I'm trying to change the name of all profiles whose name is John to Mike queryset = Profile.objects.filter(name='John') Method 1: if queryset: queryset.update(name='Mike') Method 2: if queryset.exists(): queryset.update(name='Mike') QUESTION: Which method is more efficient? Usually, I use exists() in the same line as my filter, so it queries once. However, I'm not sure if Method 2 will make another query to the database, making it less efficient. -
Using Django to display images
I am attempting to use Django to display 3 random images from a large list of user submitted images. Each image has other values associated with it like the author, so I've been making each image a model with the image field holding the image itself. Unfortunately, I can't figure out how to randomly pick from that list and pass it in to the .html page to display it correctly. So far, I've been able to get user submitted pictures to be saved as models and submitted to a folder /media/images/. My views.py will grab 3 random and unique pictures from that folder like so: def home_view(request): form = MForm(request.POST or None) if form.is_valid(): form.save() message_list = MModel.objects.all() #Get first random file file1choice = random.choice(os.listdir(DIR)) #Get second random file file2choice = random.choice(os.listdir(DIR)) while(file2choice == file1choice): file2choice = random.choice(os.listdir(DIR)) #Get third random file file3choice = random.choice(os.listdir(DIR)) while(file3choice == file1choice or file3choice == file2choice): file3choice = random.choice(os.listdir(DIR)) context = { 'file1': file1choice, 'file2': file2choice, 'file3': file3choice, } return render(request, "home.html", context) In my .html file that the user sees, I access each image passed like so: <img src="/media/images/{{ file1 }}" width="300" height="180" alt=""> Unfortunately, this doesn't allow me to actually access the … -
Why does django send_mail fails to send email with no errors?
I want to use send_mail in django, however it doesn't send any email. Here is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'MY-GMAIL-USERNAME@gmail.com' EMAIL_HOST_PASSWORD = 'MY-GMAIL-PASSWORD' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = DEFAULT_FROM_EMAIL Then, I run python manage.py shell: from django.conf import settings from django.core.mail import send_mail subject = 'Test Subject' message = 'Test Message' email_from = settings.EMAIL_HOST_USER recipient_list = ['MY-YAHOO-USERNAME@yahoo.com'] send_mail(subject, message, email_from, recipient_list) It doesn't send the email and it prints: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Test Subject From: MY-GMAIL-USERNAME@gmail.com To: MY-YAHOO-USERNAME@yahoo.com Date: Mon, 09 Dec 2019 21:02:16 -0000 Message-ID: <157592533640.18842.5494330274157836181@thinkpad-e560> ------------------------------------------------------------------------------- 1 Test Message which seems to have no errors. Why doesn't it send the email? What is wrong? Why doesn't it log any errors? I've tried a pure python way and it works fine: import smtplib, ssl smtp_server = "smtp.gmail.com" port = 465 sender_email = "MY-GMAIL-USERNAME@gmail.com" password = 'MY-GMAIL-PASSWORD' receiver_email = 'MY-YAHOO-USERNAME@yahoo.com' context = ssl.create_default_context() server = smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) server.login(sender_email, password) server.sendmail(sender_email, receiver_email, 'Test Message') As I mentioned, this pure python way works fine! I'm confused. What did I do wrong? -
Why can't I PATCH Django REST Framework PrimaryKeyRelatedField to empty list?
I'm running into a weird issue in Django REST Framework. I'm attempting to add & remove groups to/from users using PATCH requests. I am able to PATCH to /api/users/:id/ to update the groups list, which is initially empty. For example, the following actions yield these results: PATCH /api/users/:id/ {"groups": [1]} -> Results in user with groups: [1] PATCH /api/users/:id/ {"groups": [1, 2]} -> Results in user with groups: [1,2] PATCH /api/users/:id/ {"groups": [1]} -> Results in user back to groups: [1] So I am successfully updating the state with PATCH requests. However the following fails to update accordingly: PATCH /api/users/:id/ {"groups": []} -> Results in user still at groups: [1] Here is my UserSerializer class: class UserSerializer(serializers.ModelSerializer): groups = serializers.PrimaryKeyRelatedField(many=True, queryset=Group.objects.all(), allow_empty=True, required=False) class Meta: model = User fields = ( 'id', 'username', 'first_name', 'last_name', 'is_staff', 'is_authenticated', 'is_superuser', 'email', 'groups' ) My suspicion is that it has something to do with PrimaryKeyRelatedField - I have tried many combinations of arguments to the constructor to no avail. -
My form does not send data to the db django
My form does not send data to the database. I have a form that after entering data and clicking 'Order' should send information to the database. However, this does not happen. It is a 'cart' which, after sending the data, should save in the Order table information provided by the user as well as data on ordered products. cart/views.py def cart_detail(request, total=0, counter=0, cart_items = None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass if request.method == 'POST': total = request.POST['total'] billingName = request.POST['billingName'] billingAddress1 = request.POST['billingAddress1'] billingCity = request.POST['billingCity'] billingPostcode = request.POST['billingPostcode'] billingCountry = request.POST['billingCountry'] shippingName = request.POST['shippingName'] shippingAddress1 = request.POST['shippingAddress1'] shippingCity = request.POST['shippingCity'] shippingPostcode = request.POST['shippingPostcode'] shippingCountry = request.POST['shippingCountry'] order_details = Order.objects.create(total=total, billingName=billingName, billingAddress1=billingAddress1, billingCity=billingCity, billingPostcode=billingPostcode,billingCountry=billingCountry, shippingName=shippingName, shippingAddress1=shippingAddress1, shippingCity=shippingCity, shippingPostcode=shippingPostcode, shippingCountry=shippingCountry) order_details.save() for order_item in cart_items: oi = OrderItem.objects.create( product = order_item.product.name, quantity = order_item.quantity, price = order_item.product.price, order = order_details ) oi.save() '''Reduce stock when order is placed or saved''' products = Product.objects.get(id=order_item.product.id) products.stock = int(order_item.product.stock - order_item.quantity) products.save() order_item.delete() '''The terminal will print this message when the order is saved''' print('The order has been created') return redirect('cart:cart_detail') return render(request, 'cart/cart.html', dict(cart_items …