Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Output_field exists in local version but not on website, version of python and django is the same
I have a Django website locally and as a hosted version (local version for tests and development). It uses the same version for everything (Python 3.9, Django 3.1.3). I never had any problems with features working in one of the instances and not the other. I am trying to multiply two attributes for every object and then add it together. (it calculates the total weight so: weight*quantity+weight*quantity+.... The problem appeared when I tried using ExpressionWrapper. Everything works great locally but not on hosted version. Here's the line that causes error and the error itself. waga = Produkt.objects.filter(zamowienie=138).aggregate(sum=ExpressionWrapper(Sum(F('waga') * F('ilosc')), output_field=DecimalField()))['sum'] Error: Exception Type: FieldError Exception Value: Expression contains mixed types: DecimalField, IntegerField. You must set output_field. Exception Location: /usr/home/stolarz/.virtualenvs/venv/lib/python3.9/site-packages/django/db/models/expressions.py, line 303, in _resolve_output_field As you can see the error states I did not use output_field but i clearly did. I'm a bit confused. What could possibly cause this situation? -
Django Tests - User Factory with create_batch
Ok I've faced interesting problem with my tests files. I'm using this simple code to check User's created by UserFactory UserFactory.create_batch(4) for u in User.objects.all(): print(u.email) UserFactory - this works fine Creates 4 users in create_batch(4) process from django.contrib.auth import get_user_model from factory import Faker from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): email = Faker("email") password = Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ) class Meta: model = get_user_model() django_get_or_create = ["email"] UserFactory - this one doesn't work Creates only 1 user in create_batch(4) process from django.contrib.auth import get_user_model from faker import Faker from factory.django import DjangoModelFactory fake = Faker() class UserFactory(DjangoModelFactory): email = fake.email() password = fake.password() class Meta: model = get_user_model() django_get_or_create = ["email"] The only difference is the way I generate user's email. factory.Faker("email) works fine but faker.email() doesn't. Maybe someone had the same issue? factory_boy docs: https://factoryboy.readthedocs.io/en/stable/index.html faker package docs: https://faker.readthedocs.io/en/master/index.html -
JSONDecodeError at /spotify/redirect
def spotify_callback(request, format = None): code = request.GET.get('code') error = request.GET.get('error') response = post('http://accounts.spotify.com/api/token', data = { 'grant-type' :'authorization_code', 'code' : code, 'redirect_uri': REDIRECT_URI , 'client_id' : CLIENT_ID, 'client_secret': CLIENT_SECRET }).json() I am trying to work with Spotify's API but when I sent a request for post with the data shown below it's saying Json decode error. Someone please help -
Nginx and gunicorn are working fine, but site cannot be connected. How can I solve this problem?
I am not good in English. I hope you understand. I want to deploy the django project using AWS EC2. (instance settings: Ubuntu Server 18.04 LTS ... , t2 micro) + RDS + Gunicorn + Nginx I finished all the setup of ec2. Python manage.py runserver 0.0.0.0:8000 works fine. gunicorn --bind 0.0.0.0:8000 Backend.wsgi:application works fine too. But when sudo systemctl gunicorn start, when I connect to http://{mypublic IPv4}, the site cannot be connected. my /etc/systemd/system/gunicorn.service (venv) ubuntu@ip-172-31-32-142:~/diary-with-pet/Backend$ cat /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/diary-with-pet/Backend/Backend ExecStart=/home/ubuntu/diary-with-pet/Backend/venv/bin/gunicorn \ --workers 3 \ --bind unix:/home/ubuntu/diary-with-pet/Backend/run/gunicorn.sock \ --workers 3 --bind 0.0.0.0:8000 Backend.wsgi:application [Install] WantedBy=multi-user.target when I start gunicorn, (venv) ubuntu@ip-172-31-32-142:~/diary-with-pet/Backend$ sudo systemctl start gunicorn (venv) ubuntu@ip-172-31-32-142:~/diary-with-pet/Backend$ sudo systemctl enable gunicorn (venv) ubuntu@ip-172-31-32-142:~/diary-with-pet/Backend$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: Active: active (running) since Mon 2021-04-19 05:15:22 UTC; 1 day 5h ago Main PID: 9679 (gunicorn) Tasks: 4 (limit: 1140) CGroup: /system.slice/gunicorn.service ├─9679 /home/ubuntu/diary-with-pet/Backend/venv/bin/python3 /home/ubu ├─9700 /home/ubuntu/diary-with-pet/Backend/venv/bin/python3 /home/ubu ├─9702 /home/ubuntu/diary-with-pet/Backend/venv/bin/python3 /home/ubu └─9703 /home/ubuntu/diary-with-pet/Backend/venv/bin/python3 /home/ubu Apr 19 05:15:22 ip-172-31-32-142 systemd[1]: Started gunicorn daemon. Apr 19 05:15:22 ip-172-31-32-142 gunicorn[9679]: [2021-04-19 05:15:22 +0000] [96 Apr 19 05:15:22 ip-172-31-32-142 gunicorn[9679]: [2021-04-19 05:15:22 +0000] [96 Apr 19 05:15:22 ip-172-31-32-142 gunicorn[9679]: … -
Django Restframework Optimization
I have several models: LessonSession, Lesson, Receipt, and Student Lesson to LessonSession is 1 to Many Lesson to Student is M2M Receipt to Lesson is M2M Student to Receipt is 1 to Many I have a serializer that serializes LessonSession, and I want to get student's name inside Student and Receipt's id so I have receipts = self.lesson.receipt_set.all().select_related('student').values_list('id', 'student__name', named=True) as a property of LessonSession However, I cannot seem to correctly prefetch the receipt and student from LessonSession to avoid the N+1 problem. right not I have session = LessonSession.objects.all().prefetch_related('lesson').prefetch_related('lesson__students').prefetch_related('lesson__receipt_set') and I still run into N+1 problem. How should I form my queryset to avoid this? -
Running a system check after AppRegistry is initialized - Django Admin
I'm looking to run a specific check, to make sure that Django Admin classes (ModelAdmin, TabularInline etcetera) used within the project (within multiple apps) are using or inheriting from a class (a mixin in this case) - although a system check would fail since the AppRegistry is not yet loaded. I'm using the below as of current; although this raises that the AppRegistry is not loaded. from django.contrib.admin.sites import all_sites from django.core.checks import register, Error @register() def check_django_admin_inheritance(app_configs, **kwargs): errors = [] for admin_site in all_sites: for model, admin in admin_site._registry.items(): if MyMixin not in admin.__class__.__bases__: errors.append([ Error('All admin sites should derive from the MyMixin (common.django_admin)', hint='Inherit from MyMixin or use our custom ModelAdmin (common.django_admin)', obj=admin, id="id-here") ]) return errors Is there any other way around this; besides the AppConfig.ready() which would require that I place it in every application - I'm more looking towards a solution that is clean and centralized. -
Why I sometime get Coroutine was never awaited when I use asyncio.run
This error is rare, but still present. This happens when two or more requests are sent at the same time. I try to do it: adapter = OperatorCreator.create( title=operator.slug, api_key=operator.api_discount[0] ) terminals = asyncio.run( adapter.find_terminals(locality=locality), debug=True ) return terminal Adapter: async def find_terminals(self, locality: Locality, session: aiohttp.ClientSession = None) -> Mapping[str, Terminal]: if 'dpd_terminals' in cache: terminal_list = await sync_to_async(cache.get)('dpd_terminals') else: terminal_list = await self.add_terminals_from_request_to_cache() terminals = terminal_list[str(locality.kladr)] return terminals And then sometime I get: django_1 | /app/project/apps/geo/services.py:383: RuntimeWarning: coroutine 'CdekAdapter.find_terminals' was never awaited django_1 | adapter.find_terminals(locality=locality) django_1 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback What am I doing wrong? -
Django - Pass Object after redirect
I am building a scrum app where users can create user stories and add them to sprints. I want to have two separate ways of creating stories. If the user is creating a story from the backlog, the story that has been created will not be assigned to a sprint, but the user can also add a story from a sprint's detail screen. I want to make it so that if they add a story from a specific sprint's page, that story's sprint field is populated with that sprint. The way I have tried to go about this is by creating two different functions in my views.py file and two separate templates. I am able to create the story without relating to a sprint as intended, but I cannot think of a way to get the id of the sprint where I navigated from to get to the new template. For reference I have included my function for creating stories without relating to a sprint: def create_story(response, id=None): user = response.user if response.method == "POST": form = CreateNewUserStory(response.POST) if form.is_valid(): name = form.cleaned_data["name"] description = form.cleaned_data["description"] status = form.cleaned_data["status"] assignee = form.cleaned_data["assignee"] estimate = form.cleaned_data["estimate"] userstory = UserStory(name=name, description=description, status=status, … -
deleting multiple records from table in django with checkbox using ajax
I am new to Django and I'm trying to delete multiple leads from a table in my Django application and everything works fine except when i try to do the #select_all checkbox in thead of the table, i get an error such as this in the console: jquery-3.6.0.js:10109 POST http://127.0.0.1:8000/leads/delete/ 500 (Internal Server Error) Here is my code... views.py from django.shortcuts import render, reverse, redirect from django.views import generic from django.contrib import messages from .forms import LeadModelForm from .models import Lead class LeadCreateView(generic.CreateView): model = Lead template_name = "leads/lead_create.html" form_class = LeadModelForm def get_success_url(self): return reverse("leads:lead-index") class LeadUpdateView(generic.UpdateView): model = Lead template_name = "leads/lead_update.html" form_class = LeadModelForm def get_success_url(self): messages.info(self.request, "Lead updated successfully.") return reverse("leads:lead-index") class LeadIndexView(generic.ListView): queryset = Lead.objects.all() paginate_by = 25 template_name = "leads/lead_index.html" def lead_delete(request, pk): lead = Lead.objects.get(id=pk) lead.delete() return redirect("/leads") class LeadView(generic.View): def get(self, request): allleads = Lead.objects.all() context = { 'leads': allleads } return render(request, "leads/lead_index.html", context) def post(self, request, *args, **kwargs): if request.method=="POST": lead_ids=request.POST.getlist('id[]') for id in lead_ids: lead = Lead.objects.get(pk=id) lead.delete() return redirect("/leads") urls.py from django.urls import path from .views import LeadCreateView, LeadUpdateView, lead_delete, LeadView, LeadIndexView app_name = "leads" urlpatterns =[ path('', LeadIndexView.as_view(), name='lead-index'), path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'), path('create/', LeadCreateView.as_view(), name='lead-create'), path('<int:pk>/delete/', lead_delete, … -
Django - ModuleNotFoundError: No module named 'taggit_serializer' in SSH server
I installed 'taggit_serializer' in my django application. It works fine in the local server and I am able to see tags in the response from the serializer. But now I have to deploy it to the server. For that, I have to go to putty and activate the environment. I activate the virtual env and installed the package and it's successfully installed. But when I try to run python manage.py showmigrations it shows the above error. If I try to install the package again, it says the requirement already satisfied. I am not sure what is happening. Traceback: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'taggit_serializer' My serializer: from taggit_serializer.serializers import (TagListSerializerField, TaggitSerializer) class … -
How to make a GET request in an extended Django template
I have a simple navigation bar base.html, that contains links to other pages. Currently, I am extending the base.html template on every other page I have. I want to call a GET request from a weather API in order to display simple information like the city name and current temperature and have it displayed on the navigation bar. Since the base.html template isn't linked with a view itself, I am unsure how to go about this. I have already managed to succesfully get information from the API and display the information in a test page. base.html: <body> <div class="container-fluid bg-light"> <div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start"> <i class="far fa-newspaper fa-5x"></i> <a href="{% url 'news_list:homepage' %}" class="nav-link link-dark display-4">Ziņu portāls</a> <ul class="nav align-items-center ms-auto me-auto"> <li><a href="{% url 'news_list:all_posts' %}" class="nav-link link-dark pt-4"><h2>Visi raksti</h2></a></li> <li><a href="{% url 'news_list:new_post' %}" class="nav-link link-dark pt-4"><h2>Pievienot rakstu</h2></a></li> <li><h2>Information from API</h2></a></li> </ul> </div> <hr/> </div> {% block content %}{% endblock content %} </body> -
TemplateSyntaxError at /register Invalid block tag on line 6: 'csrf_tocken', expected 'endblock'. Did you forget to register or load this tag?
my code TemplateSyntaxError at /register Invalid block tag on line 6: 'csrf_tocken', expected 'endblock'. Did you forget to register or load this tag? -
how to fetch many to many fields in Django models or Django ORM
I have two classes , now I have user id only in the view , what is the Django ORM query to display the badges associated with the user,by using user id field class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.CharField(max_length=50, unique=True) user_badges = models.ManyToManyField(Badges,related_name='badges', null=True,blank=True,) class Badges(models.Model): badge_text = models.CharField(max_length=50) badge_color = models.CharField(max_length=50 -
How to add an extra weight to networkx graph?
I'm doing a Django project, where I put 2 points and get their distance. But, there are two types of weight, I need to get the length of the cable line, and length of the trakt line. Graph is able to get only one weight, How I can add an extra weight, for example, weight1, weight2? def get_distance_length_kls(request, pk1, pk2): point1 = get_object_or_404(Point, pk=pk1) point2 = get_object_or_404(Point, pk=pk2) g = nx.Graph() data = [] content = {'points': None} content1 = {"sum_line": 0, "sum_cable": 0} for form in Form61KLS.objects.all(): g.add_edge(form.point1.point, form.point2.point, weight=form.total_length_line) #here should be another type of length weight=form.total_length_cable) for p in nx.all_simple_edge_paths(g, source=point1.point, target=point2.point): finish_total = copy.deepcopy(content) finish_total['points'] = p data.append(finish_total) path = [] for p in nx.all_simple_paths(g, source=point1.point, target=point2.point): path.append(p) if len(path) > 1: for pt in path: total = copy.deepcopy(content1) path_length = nx.path_weight(g, pt, weight='weight') total['sum_line'] = path_length data.append(total) return JsonResponse(data, safe=False) ``` My output should look like this: **[ { "points": [ [ "UZB/UT/Андиж", "UZB/UT/Пахта" ], [ "UZB/UT/Пахта", "UZB/UT/Тшк" ], [ "UZB/UT/Тшк", "KAZ/ V-Net/Алматы" ] ] }, { "sum_line": 190.103, "sum_cable": 0 } ]** -
How to send looping items into ajax in Django? {% for item in items %} {{ item }} {% endfor %} How to pass all items in a single call of ajax?
All of the names need to call using ajax! Code for ajax I have tried. <script type="text/javascript"> $(document).on('submit','#form',function(e){ e.preventDefault(); alert("No reload") $.ajax({ type:'POST', url:'add-result', data:{ subject:$('#subject').val(), **//How to get all names from loop here?** names:$('#names').val(), test_score:$('#test_score').val(), exam_score:$('#exam_score').val(), class:$('#class').val(), exam_term:$('#exam_term').val(), exam_date:$('#exam_date').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), success:function (){ alert("Here") }, }, success:function (){ alert("Working !") } }); }); </script> -
How to parse an RPCReply python3
Hello I am currently on a project that is not mine and needs updating, I am stuck here, trying to parse an rpc-reply into a string so it can be parse into an xml.The whole project was coded by somebody else and he/she used python2 and now I am required to use python 3.6 but it does not work I have tried some alternatives that I have found online but none of them work (such as this https://mihird.com/parsing-junos-rpc-reply-with-beautifulsoup4/ ) This are the functions giving me issues, the response parameter is <class 'ncclient.operations.rpc.RPCReply'> def is_successful(response): import io doc = parsexml_(io.StringIO(response)) rootNode = doc.getroot() success_list = rootNode.xpath("//*[local-name()='ok']") if len(success_list) > 0: return True, None else: reason_return = '' reason_list = rootNode.xpath("//*[local-name()='error-message']") for reason in reason_list: reason_return = '%s %s' % (reason_return, reason.text) return False, reason_return def parsexml_(*args, **kwargs): if 'parser' not in kwargs: kwargs['parser'] = ET.ETCompatXMLParser() doc = ET.parse(*args, **kwargs) return doc Thanks you so much for the help in advance! -
Login using Post Request of a website and going to the next url from backend using Http(Django) [closed]
Login using Post Request of a website and going to the next URL from backend using HTTP(Django) -
Django Channels Send Msg (Hyperlink)
I studied Django Channels The chat room has been established But i have a problem now If the client sends a http:// message How to make the http message displayed in the chat room have a hyperlink function? Should it be processed on the front-end or on the back-end? -
Synch between Django runserver & Selenium Webdriver
okay so I have made an app from where django webapp will take a id & date-of-birth as input and it will return some json HTTPResponse with details after parsing it from other websites. I have done this with Selenium integration where I have a "Driver" variable in settings.py because I want the Selenium driver to run one time while executing the Django Server and it will be in that background process state while the Django server is running. Now my Question is How can I remove the Driver object because if restart the server the Firefox(Driver) is still in the process. Is there any way to delete the old process and instantiate again with new instance. views.py def search(request): if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): nid = form.cleaned_data['nid_number'] dob = form.cleaned_data['date_of_birth'] json = SearchAction(settings.WEBDRIVER_WINDOW, nid, dob) return HttpResponse(json, content_type="application/json") else: if request.GET.get('nid') and request.GET.get('dob'): nid = request.GET.get('nid') dob = request.GET.get('dob') json = SearchAction(settings.WEBDRIVER_WINDOW, nid, dob) return HttpResponse(json, content_type="application/json") else: form = RequestForm() context = { 'title': "Search NID", 'form': form } return render(request, 'voter_id_parser/search.html', context) browser.py class SingletonBrowser: options = Options() options.add_argument("--headless") __instance = None @staticmethod def get_browser() -> webdriver: if SingletonBrowser.__instance is None: SingletonBrowser() return … -
Showing who viewed the post ( user )
I am building a BlogApp and I build a feature, So i can count post views. BUT i am trying to get who viewed the Post. views.py queryset = BlogPost.objects.annotate(num_views=Count('viewers')).order_by('-num_views') datas = get_object_or_404(queryset,pk=pk) if request.user.is_authenticated: created = Post.viewers.through.objects.get_or_create(post=datas,user=request.user) Below code counts the views of Post whenever i print {{ datas.viewers }}, BUT when i try to print {{ datas.viewers.user.username }} then, It doesn't show the viewed users class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') viewers = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='viewed_posts',editable=False) BUT i am trying to show `who viewed the BlogPost. Any help would be Appreciated. Thank You in Advance. -
Django save function model: How to assign "data_counter" as number series when importing from excel file
This is a continuation of these questions: Django: Generate a custom series number upon saving the model https://stackoverflow.com/q/67084479/2380028 I have a scenario of generating series number per location id, which I was able to solved in the above link. Now, my concern is: How can I assigned the data_counter as series number when importing an excel file using the django-import-export? As of now, if I will add a new instance via admin site, the save function is working as intended, but when adding a new instance (bulk) via import function, everything is messed up and I cannot edit the whole property number field xD, below is the result: As you can see in the image, the series number is the second to the last group (4-digit) and the location id is the last group (2-digit) The first 9 data should be like these: 1972-30-40-0001-00 1972-30-40-0002-00 1972-30-40-0003-00 1972-30-40-0004-00 1972-30-40-0001-18 1972-30-40-0005-00 1972-30-40-0001-19 1972-30-40-0002-19 1972-30-40-0006-00 and so on... save funtion def save(self, *args, **kwargs): data_counter = Item.objects.filter(location=self.location).aggregate(counter=Count('id'))['counter'] # Count existing instance with matching "location id" of the new instance if self.pk is None and self.property_number is None: # if new instance and property number field is blank if data_counter is None: # if … -
django csrf token : CSRF token missing or incorrect
I don't use a django form, we only process it with API and respond to the result. When using a form, I know that you are using a tag, but in this case, it is difficult to write a tag. I can't get rid of csrf so I need help. When receiving a request as a post, "CSRF token missing or incorrect." Appears. How can I solve this problem? heres view's.py class EventsView(View): def post(self, request): json_request = json.loads(request.body) ApplyEvent.objects.create( event=event, meta_user=user ) return JsonResponse({"message": "SUCCESS"}, status=201) const response = await axios({ method: "post", url: `${apiHostName}/events`, data: { event_id: 8, user_id: `${props.userStore.user?._id}`, }, withCredentials: true, xsrfHeaderName: "csrftoken", xsrfCookieName: "X-CSRFToken", }) -
How to disable a field in wagtail when another field value changes?
I have a wagtail form as given: from django import forms from wagtail.admin.forms import WagtailAdminPageForm from myapp.models import * class MyClassForm(WagtailAdminPageForm): displayed_on_section = forms.ModelMultipleChoiceField( queryset=DisplayedOnSection.objects.all(), widget=forms.CheckboxSelectMultiple() ) last_name = forms.CharField(required=False) # other fields And my page looks like this: from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page class MyClassPage(Page): content_panels = Page.content_panels + [ FieldPanel('displayed_on_section'), FieldPanel('displayed_on_section') ] base_form_class = MyClassForm Now suppose I have 3 displayed_on_sections like: o Profile Section o Dashboard Section o Feed Section I want that if the user selects Feed Section, the last_name form field should get disabled (and if possible, its value becomes empty). Is it possible to achieve what I'm trying to do, and what are the ways to do it? P.S. I just want to know how to do this, I don't require full solution. -
Raspberry start django app while directly connected with eth0 to a pc
I have to create on my raspberry pi a django app for manage internal settings opening connecting directly a pc to my raspberry via eth0 port. As normally for example for configure routers an user can connect his PC directly to the port and typing for example 192.168.1.65 and open admin configuration panel i would the same with my raspberry. I fix the eth0 address in my /etc/dhcpc.conf to 192.168.1.50, then i start my django app: python manage.py runserver 0.0.0.0:8000 but if i connect my raspbery to local lan, from another pc via network on 192.168.1.50:8000 i see django screen correctly, but if i connect directly Pc to raspberry i get "Cannot connect, timeout" How can i open my app from a specific Ip address connecting directly a PC to my device? So many thanks in advance -
"<Order: Order object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used
So I'm trying to add multiple products or order items into a product and I'm using many to many relationship for that but when I try to create that order I get "<Order: Order object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. error, My code for adding and saving that order is like: userObject = UserLogin.objects.get(token=finalUserToken).user objects = OrderItem.objects.filter(user=userObject) FinalOrder = Order(user=userObject, order_id=another_token) for orderObject in objects: FinalOrder.products.add(orderObject.id) FinalOrder.save() The error screen is pointing to this line FinalOrder.products.add(orderObject.id) I have also tried this FinalOrder.products.add(orderObject) but this gives the same result too