Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem sending code from Azure DevOps to Azure App Service
I am having a performance problem between Azure DevOps and Azure App Service. I'm developing in Django. In Azure DevOps I have a build pipeline that creates a zip file, then I have a release pipeline that sends that file to Azure App Service. Doing this does not work, but if in Azure App Service, in the deployment center I remove the connection to Azure DevOps, I make a connection to GitHub and there I put the same code that I tried previously, then it works. I have invested many hours and I cannot find the problem. Are there ways to view logs in Azure App Services? Is there a file explorer? Build pipeline configuration: #Multi-configuration and multi-agent job options are not exported to YAML. Configure these options using documentation guidance: https://docs.microsoft.com/vsts/pipelines/process/phases pool: name: Azure Pipelines variables: python.version: '3.8' steps: task: UsePythonVersion@0 displayName: 'Use Python $(python.version)' inputs: versionSpec: '$(python.version)' script: 'python -m pip install --upgrade pip && pip install -r requirements.txt' displayName: 'Install dependencies' script: 'pip install flake8 && flake8' displayName: Flake8 enabled: false continueOnError: true script: 'pip install pytest && pytest tests --doctest-modules --junitxml=junit/test-results.xml' displayName: pytest enabled: false task: PublishTestResults@2 displayName: 'Publish Test Results /test-results.xml' inputs: testResultsFiles: '/test-results.xml' testRunTitle: … -
how to add a combobox with the groups in sqlite in sign up form django
I need help with the sign up form. I want to add a combo box in the form where the users register, this combobox have to have as options the groups that are created in sqlite. How can i do this, please help me -
Add data to a form in `CreateView`
I have a model which the user submits on a form, and I would like to handle that form with a CreateView. However, there is one field in the model which the user doesn't provide, which is their IP address. The problem is that the CreateView fails with an IntegrityError since the field is empty. I tried modifying request.POST to add the relevant field, but that's not allowed (and a bad idea). I figured I could use a hidden input on the form and put the IP there but that means the user can blank it or modify it if they like, I want the exact IP that did the POST request. If I understand correctly both the form_valid and form_invalid methods are too early in the process, since the object hasn't been created yet? Is there any other way of doing this? -
What should I do making a template using vue.js in django
I want to customize a template on django and use vue.js on that. What steps should I follow. What should I do first? Should I make a template on django and then vue? Please its urgent. -
How to get Nested array from local storage in javascript
I am storing user data in local storage after successful user login in angular let authObservable: Observable<any>; authObservable = this._authService.login(this.f.email.value, this.f.password.value); authObservable.subscribe( result=> { localStorage.setItem('id', result['id']); localStorage.setItem('username', result['username']); localStorage.setItem('email', result['email']); localStorage.setItem('tokens', result['tokens']); } but token contain another array "id": "user_id" "tokens": "{'access': 'access_token', 'refresh': 'refresh_token_value'}" "username": "username value" how can i get tokens value and access token value and store it in refresh_token and access_token variables. -
Djoser 400 Bad request login users
I'm creating an e-commerce app with django rest framework and vue, I'm using djoser.authtoken to handle authentications. I could successfully create a user with a post request to /users/ but whenever I try to log in I keep getting xhr.js:177 POST http://127.0.0.1:8000/api/v1/token/login/ 400 (Bad Request) in the console and [22/May/2021 03:06:11] "POST /api/v1/token/login/ HTTP/1.1" 400 68 on the server. The error messages aren't giving any useful info but here are some of the relevant snippets for my code: # myproject/urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('api/v1/', include('product.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'product', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:3000", "http://127.0.0.1:3000", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] // axios request await axios .post('/api/v1/token/login/', formData) .then(res => { const token = res.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common['Authorization'] = 'Token ' + token localStorage.setItem('token', token) const toPath = this.$route.query.to || '/cart' this.$router.push(toPath) }) .catch(err => { if(err.reponse){ for (const property in err.response.data) { this.errors.push(`${property}: ${err.response.data[property]}`) } } else { console.log(err) } … -
Handling images files on the backend in Django Rest sent from an array on the frontend
I am not sure the backend has to do anything with it ie this has to be solved by only frontend. I have post API where data is to be sent like this. { "merchant": 2, "category": [ 7 ], "brand":7 , "name":"picture55test", "best_seller":true, "top_rated":false, "collection":10, "description":"abc", "featured": false, "availability": "in_stock", "warranty": "no_warranty", "rating":5, "picture": [], "services": "cash_on_delivery", "variants": [ { "product_id": "OAXWRTZ_12C", "price": "500.00", "size": "not applicable", "color": "not applicable", "variant_image": null, "quantity": 10, "variant_availability": "available" }, { "product_id": "OGROUPIRZ_12C", "price": "888.00", "size": "not applicable", "color": "not applicable", "variant_image": null, "quantity": 10, "variant_availability": "available" } ] } I am here trying to create a product object creating the variants objects at the same time. The issue is it works the frontend is not being able to send image from array of variants which is vairant_image in the form-data. The payload headers look like this As you can the variant fields like coming like an object instead of a form-data. I dont know how to handle this in backend?? My view looks like this. I have used FormParser and Multipartparser just in case it handles the image. I just dont know if this is to be handled from frontend or … -
Pass a variable in the html template in django
I need to create an html django template a paragraph with a select dinamically created. I read values from a txt file and I store it in a dict, when I call the render to response I pass this dict but when I try to print its values in the template it doesn't print anything. This is my views: views.py def index(request): context = { 'variable': 'This has been sent' } return render(request, 'index.html', context) and this is the print in the html template: And this is the variable I'm calling in the HTML template: index.html <p>Hey Dear! {{variable}}</p> Can anyone help me? -
How to create files to avoid permission issues in docker?
I am new using docker and i have a task to create two containers: one for a django project and another for a mysql server. I made it using Dockerfile and docker-compose.yml. The project it's working with "docker-compose up", but i have permission problems when i try to create new files inside the container with "python manage.py startapp app_name". Basically i can't modify the files inside my ide(pycharm ubuntu). For what i can understand the user in the docker is root, so i need to have root permission to change those files but i don't want to modify them as root or change the permission of those files each time i make them. Here is my Dockerfile: FROM python:3.9.5 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8000 docker-compose.yml version: "3.9" services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:/app depends_on: - mysqldb mysqldb: image: mysql:5.7.34 restart: always environment: MYSQL_DATABASE: mydb MYSQL_USER: django MYSQL_PASSWORD: djangopass MYSQL_ROOT_PASSWORD: mysecretpassword volumes: - .dbdata:/var/lib/mysql ports: - 3306:3306 -
in react i had taken input file and trying to send to django server using redux dispatch action but file is empty in request.data
[ReportProblemActionTypes.SEND_REPORT_PROBLEM_FORM](state: reportProblemState):reportProblemState { return { ...state, sending: true, success: false, errors: {}, loading: true }; }, -
How to access 'related_name' of a model via intermediate model's Foreign key inside template tag?
models.py class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) ... class Review(models.Model): paper = models.ForeignKey(Book, null=True, on_delete=models.CASCADE, related_name='book_class_related_name') user = models.ForeignKey(User, on_delete=models.CASCADE) comment = RichTextField() status = models.CharField(max_length=10, choices=options, default='draft') ... class TrackReviewRequests(models.Model): paperid = models.ForeignKey(Book, null=True, on_delete=models.CASCADE, related_name='book_track') numberOfTimesReviewRequestSent = models.PositiveSmallIntegerField(default=0) ... views.py reviews_in_draft = Review.objects.filter(paper__active=True).filter(status='draft') return render(request, 'accounts/profile.html', { 'reviews_in_draft': reviews_in_draft, }) profile.html Here I tried accessing the 'numberOfTimesReviewRequestSent' using the following code: {% for review in reviews_in_draft %} {{ review.paper.book_track.numberOfTimesReviewRequestSent }} {% endfor %} But I am getting empty string. Then I wrote a method inside the Book model def get_TrackReviewRequests_numberOfTimesReviewRequestSent(self): return self.book_track.numberOfTimesReviewRequestSent and tried accessing the numberOfTimesReviewRequestSent in the profile.html using the following code: {{ review.paper.get_TrackReviewRequests_numberOfTimesReviewRequestSent }} But this time I got the error stating 'RelatedManager' object has no attribute 'numberOfTimesReviewRequestSent' Ultimately, I want to access the numberOfTimesReviewRequestSent in the template using the context variable. -
I'm trying to create a website through Vue and a DJango, and I wonder if this is right
As far as I know, Django processes the data as a back-end and delivers the data processed as a front-end. Then I'd like to process the API at back-end and deliver it to the front. I want to put API data in the designed model and hand over this model to Vue I wonder if it usually takes a long time to get 50 saved data. so I wonder if this is the right way and is there any solutions for this? -
How to have nested Orderables?
We have a content model with a couple of many-to-many (type) relationships: Issue has many Articles Article has many Authors In this specific case, our Article and Author models are fairly small. The use case is to construct a table of contents for a magazine Issue by creating a list of Article titles and one or more Authors for each Article. Ideally, the end-user could edit the entire Issue from a single form, since the articles are only used as a table of contents. I have tried to model this using the Page and Orderable classes, as follows. However, I am getting a KeyError when wagtail attempts to render the Issue edit form. class Author(Orderable): """ Represents authorship for an article allowing multiple authors per article and multiple articles per author """ article = models.ForeignKey( "magazine.Article", null=True, on_delete=models.PROTECT, related_name="authors", ) author = models.ForeignKey( "wagtailcore.Page", null=True, on_delete=models.PROTECT, related_name="articles_authored", ) panels = [ PageChooserPanel( "author", ["contact.Person", "contact.Organization"] ) ] class Article(Orderable): """ An article, which can have multiple authors """ title = models.CharField(max_length=255) issue = ParentalKey( "magazine.ArchiveIssue", null=True, on_delete=models.PROTECT, related_name="articles", ) panels = [ FieldPanel("title", classname="full"), # Multiple authors can contribute to an article InlinePanel( "authors", heading="Authors", help_text="Select one or more authors, … -
Django & Sqlite Database Access : No such table
I have a django & docker server running on my computer and I have created a database with code from outside this server. I am trying to access this database ('test.sqlite3') within the server. I made sure the path was the correct one and that the file name was correct as well. When I open the database with DB Browser, I can see the tables and all my data. But I still get the following error text: OperationalError no such table: NAMEOFTABLE When I use the exact same code from another python IDE (spyder) it works fine. I'm guessing there's something weird going on with django? Here is some of the code: conn = sqlite3.connect("../test.sqlite3") c = conn.cursor() c.execute("SELECT firstName, lastName FROM RESOURCES") conn.close() (Yes, I have also tried using the absolute path and I get the same error.) -
How to test Custom User model in Django fir a simple model used to track the data of other fields?
everyone. Hope you're doing well. So, I have two models, my main model where I have the data that goes to my endpoint, and a second model that I'm using to store the changes made to a field of the main model. They're very simple, like this: Main Model: . class MyModel(TimeStampedModel, models.Model): """A simple model""" field_1 = models.CharField(max_length=255, null=True, blank=True) field_2 = models.CharField(max_length=255, null=True, blank=True) choice_field = models.CharField( max_length=32, choices=ChoiceModel.choices, default=None, null=True, blank=False ) . . . 2.. And a Model used to store changing data of MyModel: Class MyModelHistory(models.Model): choice_field_from = models.CharField(max_length=32, null=True, blank=False) choice_field_to = models.CharField(max_length=32, null=True, blank=False) changed_at = models.DateTimeField() user = models.CharField(max_length=55) my_model = models.ForeignKey(MyModel, on_delete=models.CASCADE) I'm only interested in storing the changes made to the choices field and the User who did it, with a timestamp. But since I have a Custom User model, I'm having some issues. To connect the two models is a little tricky. We could do it with signals or by modifying the __init__ and save methods of MyModel. For my application, I HAVE to do with the latter, so here's what I did for that: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #import pdb; pdb.set_trace() if self.pk is None: self._old_choice … -
reduce the same dockerfile for multiple services from running in each service
I have three services in the docker-compose file based on python and Django And I'm using a single dockerfile for these 3 services which have python image, pip install, apt install etc. Services one for WSGI services tow for Asgi (Channels) services Three for celery This return three large-size containers and use a lot of time How can I run this large process in one container and use the cache of other containers? Dockerfile FROM python:3.8.3-alpine WORKDIR /app ADD ./backend/requirements.txt /app/backend/ RUN apk add --update \ freetype-dev \ gcc \ gdk-pixbuf-dev \ gettext \ jpeg-dev \ lcms2-dev \ libffi-dev \ musl-dev \ openjpeg-dev \ openssl-dev \ pango-dev \ poppler-utils \ postgresql-client \ postgresql-dev \ py-cffi \ python3-dev \ zlib-dev \ bash RUN pip3 install --upgrade pip RUN pip install gunicorn RUN pip3 install -r backend/requirements.txt ADD ./backend /app/backend ADD ./docker /app/docker RUN chmod +x /app/docker/backend/wsgi-entrypoint.sh RUN chmod +x /app/docker/backend/asgi.entrypoint.sh RUN chmod +x /app/docker/backend/celery-entrypoint.sh docker-compose.yml version: '3.7' services: nginx: restart: unless-stopped build: context: . dockerfile: ./docker/nginx/Dockerfile ports: - 80:80 - 443:443 volumes: - static_volume:/app/backend/server/django_static depends_on: - backend - asgiserver backend: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile entrypoint: /app/docker/backend/wsgi-entrypoint.sh volumes: - static_volume:/app/backend/server/django_static expose: - 8000 env_file: ./env/.django.prod environment: - SECRET_KEY=tv==u93r#vx(-f6xtt3&+npkjdl_h=zz6hgenha@_p=2s!!1fc - … -
I want make app in reactjs as front end and django as backend for AI project so how can I take live video feed from react
I try to run cammera on click event in reat from django url but it give error.I Want to build project using opencv .I am using reactjs as front end and django as back end from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def init(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def livefe(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it with proper handling pass -
what approch should i follow to predict gift on the basis of data given by user. I using Django framework
http://localhost:8888/notebooks/KSproject/sk.ipynb link to the project ,here i am only getting one output for any random input -
New model objects disappear after five minutes in Django
whenever I create a new object in one of my models, they exist for around five minutes and then disappear. I checked in both my admin view and the queryset in the shell and they just disappear. I don't understand what's happening so if anyone has any idea, that'd be very useful. These are the models: class Character(models.Model): image = models.ImageField() name = models.CharField(max_length=100) age = models.IntegerField() story = models.CharField(max_length=500) def __str__(self): return self.name class Movie(models.Model): image = models.ImageField() title = models.CharField(max_length=100) creation_date = models.DateField(auto_now=True) rating = models.IntegerField() characters = models.ManyToManyField(Character, blank=True, related_name='movies') def __str__(self): return self.title These are the views: class CharacterCreateAPI(generics.CreateAPIView): queryset = Character.objects.all() serializer_class = CharacterSerializer permission_classes = (AllowAny,) class MovieCreateAPI(generics.CreateAPIView): queryset = Movie.objects.all() serializer_class = MovieSerializer permission_classes = (AllowAny,) These are the serializers: class CharacterSerializer(serializers.ModelSerializer): movies = serializers.PrimaryKeyRelatedField(queryset=Movie.objects.all()) class Meta: model = Character fields = ['name', 'age', 'image', 'movies', 'story'] extra_kwargs = {'image': {'required': False, 'allow_null': True}} class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('title', 'image', 'rating', 'characters') extra_kwargs = {'image': {'required': False, 'allow_null': True}} def create(self, validated_data): characters = validated_data.pop('characters') movie = Movie.objects.create(**validated_data) if characters: movie.set(characters) movie.save() return movie -
getting a list in response of serializer
I am trying to make something like this in my serializer response - [ { "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "supporting": "id":1 , "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "id":2 , "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, } ] Instead I am getting this - [ { "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "supporting": "c5f408bd-a07f-4ee5-b7a9-b2dee8f67634" }, { "user": { "hnid": "87481adf-5a6e-4995-bb21-cc4258f97a46", "username": "Md.AbcAhmeddsf #7TJG2GLQ", "profile_img": null, "full_name": "Md. Abc Ahmeddsf" }, "supporting": "d0a04c7b-6399-44db-ba7c-4ef39ae7e59c" } ] How can I make like this .. here is my models.py class Supports(models.Model): user = models.ForeignKey(HNUsers, on_delete=models.CASCADE, related_name='supporting_user') supporting = models.ForeignKey(HNUsers, on_delete=models.DO_NOTHING, related_name="supportings") is_support = models.BooleanField(blank=True, null=True, default=False) class Meta: verbose_name_plural = "Supports" here is my Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = HNUsers fields = ( 'hnid', 'username', 'profile_img', 'full_name', ) class SupportSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, many=False) # supporting = SupportingUserSerializer(read_only=True, many=False) class Meta: model = Supports fields = ( 'user', 'supporting', ) here is my views.py @api_view(['GET', 'POST']) @permission_classes((permissions.AllowAny,)) @parser_classes([FormParser, MultiPartParser]) def create_support(request): data = request.data print(data) if request.method == … -
'Movie' object is not iterable when making a post request
I keep getting the error ''Movie' object is not iterable' when I make a post request but the instance gets created anyway so I was wondering how I can get rid of it. This is the view that throws the error when I try to create a character: class CharacterCreateAPI(generics.CreateAPIView): queryset = Character.objects.all() serializer_class = CharacterSerializer permission_classes = (AllowAny,) These are the models: class Character(models.Model): image = models.ImageField() name = models.CharField(max_length=100) age = models.IntegerField() story = models.CharField(max_length=500) def __str__(self): return self.name class Movie(models.Model): image = models.ImageField() title = models.CharField(max_length=100) creation_date = models.DateField(auto_now=True) rating = models.IntegerField() characters = models.ManyToManyField(Character, blank=True, related_name='movies') def __str__(self): return self.title These are the serializers: class CharacterSerializer(serializers.ModelSerializer): movies = serializers.PrimaryKeyRelatedField(queryset=Movie.objects.all()) class Meta: model = Character fields = ['name', 'age', 'image', 'movies', 'story'] extra_kwargs = {'image': {'required': False, 'allow_null': True}} class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('title', 'image', 'rating', 'characters') extra_kwargs = {'image': {'required': False, 'allow_null': True}} def create(self, validated_data): characters = validated_data.pop('characters') movie = Movie.objects.create(**validated_data) if characters: movie.set(characters) movie.save() return movie -
How To Store exec and render it to a template in Django?
I am creating a website where I can store my code. I also want a feature where I can run the code! So I used exec, but I can't render it to a html page. It justs prints the output to the console. This is my views.py def SeeCode(request, code_pk): code = Code.objects.get(pk=code_pk) execute = exec(code) context = { "code": code, "execute": execute } return render(request, "base/see_code.html", context) And this is my html page: {% block content %} <h1>{{ code.title }}</h1> <br><br> <div class="row"> <div class="col md-7" id="col1"> <pre><code class="python">{{code.code}}</code></pre> <br> <a class="run">Execute</a> </div> <div class="col md-4" id="col2"> <h6>OUTPUT</h6> <p>{{ execute }}</p> </div> </div> {% endblock %} Can you please tell me how to fix this? Or any alternative ways to run the python code and render it to my html page? -
Django cannot connect to postgresql docker container
I have a postgres db running in a docker container: my docker-compose: version: "3" services: db: image: postgres:13.1-alpine environment: - POSTGRES_DB=mydb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=test ports: - "5432:5432" volumes: - ./postgres_data:/var/lib/postgresql/data/ Django running on the host machine cannot connect to it. django's settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST' : "localhost", 'NAME' : "mydb", 'USER' : "postgres", 'PASSWORD' : "test", 'PORT':5432, } } Exception: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432" Database is certainly avaliable on port 5432(I can connect to it with dbeaver database client on localhost:5432). What could be the cause of the problem? -
Cookie issues with Django runing on IOS
I have a web app made using Django and uses cookies for maintance sesson because y based on chamilo LMS (it use cookies). The web app run ok in window and android devices but not in IOS devices. How is the manage for cookies in IOS? Currently I tried creating the cookie with secure check and samesite as None but the information is losing whe redirect between home and the rest of the site -
How to copy an existing django object to another table for temporary storage?
Basically I have an inventory system and a POS, cart and checkout. Here are my models: class OrderItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) qty = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=False, auto_now=True, blank=True, null=True) def __str__(self): return f"{self.item.upc} || ${self.item.sug_ind_retail} || ({self.item.item_name}) X {self.qty} " def get_total_item_price(self): return self.qty * self.item.sug_ind_retail def get_item_sales_tax(self): return self.get_total_item_price() * .095 def get_total(self): return self.get_item_sales_tax() + (self.item.sug_ind_retail * self.qty) class TempCartItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) qty = models.IntegerField(default=1) date_created = models.DateTimeField(auto_now_add=False, auto_now=True, blank=True, null=True) def __str__(self): return f"{self.item.upc} || ${self.item.sug_ind_retail} || ({self.item.item_name}) X {self.qty} " def get_total_item_price(self): return self.qty * self.item.sug_ind_retail def get_item_sales_tax(self): return self.get_total_item_price() * .095 def get_total(self): return self.get_item_sales_tax() + (self.item.sug_ind_retail * self.qty) Basically I want to save the TempCartItem's into the OrderItem model, this way I can delete all the items in the cart but save the OrderItem's when we check out a customer. Here is my view: @login_required def order_item_view(request): temp_order_item_form = TempCartItemForm(request.POST or None) if request.POST.get("submit"): temp_order_item_form.save(commit=False) form_upc = temp_order_item_form.cleaned_data.get('upc') if form_upc == '': messages.warning(request, "UPC is required to add to cart.") form_qty = temp_order_item_form.cleaned_data.get('qty') global customer customer = temp_order_item_form.cleaned_data.get('customer') # get item or create new one if …