Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i make a project in python and i want to a make web app in django i can't understand how to make web app using these function
1) Create account 2) Deposit 3) Withdraw 4) Balance Inquiry 5) All Account holder list 6) Close Account 7) update info -
Does this selection of AWS Free-Tier Services is appropriate for my web application?
Just to say that I am an absolute beginner to these concepts. My web app right now The user makes requests that Django handles as follows: 1.a) Django run queries (based on user selection) on csv files that it keeps 2.b) Django keeps also 1 small database for registered users Possible upgrade of my web app If ever I want to upgrade my app, I will replace csv files with databases (1 for each user) Note, that I have already dockerized my whole application in order to have the same development and production environment, using this architecture: 2.a) Nginx Container that sends requests either to b1 or to b2 2.b1) Angular Static Files Container 2.b2) Django App Container 2.c) Django Database Container Selected Free Tier AWS Services So, Ι have concluded the use of the follows AWS Free-Tier Services: 3.a) Angular static files -> AWS S3 and AWS Cloudfront 3.b) Django Docker Container -> AWS ECS 3.c) Django Database -> AWS RDS Questions 4.a) Does this selection of Free-Tier AWS Services make sense? 4.b) What about the consistency of development and production environments that I had using Docker before? -
How to display all my model's fields in django admin?
This code displays objects like this: Home Object(1) ,Home Object(2) but I want to display all the model fields in my django admin page.How can I do this? I am very beginner in django and this is my first project. models.py class Home(models.Model): image=models.ImageField(upload_to='home') paragraph=models.TextField() created=models.DateTimeField(auto_now_add=True) admin.py admin.site.register(Home) -
Could not submit Django form with <a> element
I'm trying to make Django submit a form with <a> element, but have GET metod instead POST <form id="add-employee-form" action="add/" method="POST"> <table> <tr> <th class="table-title" id="second-name"> Фамилия </th> <th class="table-title" id="first-name"> Имя </th> <th class="table-title" id="patronymic"> Отчество </th> <th class="table-title" id="birth-date"> Дата рождения </th> </tr> <tr> <th id="second-name"> <div class="field-wrapper"> {{ form.second_name.errors }} {{ form.second_name }} </div> </th> <th id="first-name"> <div class="field-wrapper"> {{ form.first_name.errors }} {{ form.first_name }} </div> </th> <th id="patronymic"> <div class="field-wrapper"> {{ form.patronymic.errors }} {{ form.patronymic }} </div> </th> <th id="birth-date"> <div class="field-wrapper" id="birth-date-wrapper"> {{ form.birth_date.errors }} {{ form.birth_date }} </div> </th> </tr> </table> {% csrf_token %} <div class="button_bar"> <a class="a-button positive" href="{% url 'add-employee-action' %}">Добавить</a> <a class="a-button" href="{% url 'employee' %}">Сотрудники</a> <a class="a-button" href="{% url 'index' %}">На главуную</a> </div> </form> urls.py path('employee/add_employee/add/', views.add_employee_action, name='add-employee-action'), views.py def add_employee_action(request): if request.method == "POST": form = AddEmployeeForm(request.POST) if form.is_valid(): form.save() else: form = AddEmployeeForm() context = { 'form': form, } return render(request, 'add_employee.html', context) How to submit the form using <a> element? -
How to get all user record after me from auth_user table order by date_joined in django
I'm new with django, I just want to get all user record after a specific username from auth_user table order by date_joined. Please guide or reply to your valuable response. Thanks for all! -
Django Model MultipleObjectsReturned
I am using django ORM to talk to a SQL Server DB. I used the .raw() method to run a query: @classmethod def execute_native_queries(cls, query): return cls.objects.raw(query) I later type-cast it into a list by running: data = list(modelName.execute_native_queries(query)) While iterating through the list, i would call certain columns as such: for entry in data: a = entry.colA b = entry.colB c = entry.colC For certain entries, I am able to run one loop-iteration fine, however for some i get the following error: api.models.modelName.MultipleObjectsReturned: get() returned more than one modelName-- it returned 2! What i do not get is how come this error is surfacing? -
Django not finding static js scripts in the correct folder
I've already run collectstatic and created the static directory in my urls.py, and all other static files work fine (bootstrap, the custom CSS) and other scripts in the same directory work perfectly fine. This is the error code in the console. Failed to load resource: the server responded with a status of 404 (Not Found) ... jquery.formset.js:1 (http://localhost:8000/static/js/django-dynamic-formset/jquery.formset.js) (index):86 Uncaught TypeError: $(...).formset is not a function at (index):86 This is the script section from the rendered html For the second error, I've run into a similar problem before. Moving the jQuery CDN tags above the script itself solved the issue then, but it's not working now. This is my root urls.py urlpatterns = [ path('admin/', admin.site.urls), path('showroom/', include('showroom.urls')), path('', RedirectView.as_view(url='/showroom/', permanent=True)), # Redirect homepage to showroom path('accounts/', include('allauth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py # Static and media files STATIC_URL = '/static/' STATIC_ROOT = ( os.path.join(BASE_DIR, 'static') ) MEDIA_URL = '/media/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media') ) <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="/static/js/django-dynamic-formset/jquery.formset.js"></script> <script type="text/javascript"> $('.formset_row-image_set').formset({ addtext: 'add another', deleteText: 'remove', prefix: 'image_set', }); </script> </body> For context, this is an object creation form. The script allows dynamically created server-side formsets so users can upload individual images. … -
CSRF verification failed on submit after rendering the template via Ajax before
I have a large model formset with initial data, which is injected by ajax through a seperates rendered template. I also pass the csrf token to the template. In the inspector you can also see that the csrf hidden input looks exactly like the other forms on the same page. However, if I want to submit the form, I still get a csrf error. So the complete interface works and also the token is rendered into the template, only I can't submit the form and I don't know why I already tried to render the form without input and inject the inputs via Ajax, but the result was the same. views.py that is called by ajax POST request def render_revolver_table_form(request, product_id, production_step): context = {} context['csrfmiddlewaretoken'] = _get_new_csrf_token template = 'products/product_details/setup_revolver_table.html' SetupRevolverMapFormSet = modelformset_factory(SetupRevolverMap, exclude=( 'product', 'production_step', 'kanal', 'id'), form=SetupRevolverMapForm) setup_revolver_maps = SetupRevolverMap.objects.filter( product=product_id, production_step=production_step).all() context['formset'] = SetupRevolverMapFormSet( queryset=setup_revolver_maps.filter(kanal=1)) return render(request, template, context) injected template <table class="table"> <thead class="thead-dark"> <tr> <!-- Here is content from the formset --> </tr> </thead> <form id="setup_revolver_form_kanal_1" action="" method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value={{csrfmiddlewaretoken}}" /> {{ formset.management_form }} <tbody> <!-- Here is content from the formset --> </tbody> </form> </table> ajax.js csrftoken = $('input[name="csrfmiddlewaretoken"]').val() $.ajax({ url: … -
how to call an url in django view function
I am trying to execute one of the url of urls.py with urllib in djnago view function. After execution i got error like 'url': request.get_host() + new_path, [Thu Oct 17 11:19:27.634475 2019] [wsgi:error] [pid 5120] [remote 202.88.246.2:46648] RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to app.dev-mintaka.aavso.org/member/change_password/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Is this possible to execute url with urllib inside django view function. @login_required(login_url='http://domain/user/login?destination=apps/member/change_password') def change_password(request): '''Form for user to change their password''' form = SetPasswordForm(user=request.user, data=request.POST or None) if form.is_valid(): form.save() ob = urllib.request.urlopen(url='http://app.dev-mintaka.aavso.org/login/', data=request) messages.success(request, 'Your password has been succesfully updated!') return redirect('hq:profile') return render(request, 'registration/password_change_form.html', {'form': form}) when i execute urllib -
Getting forbidden You don't have permission to access / on this server
i'm trying to deploy django application using apache & mod_wsgi on centos 7. I have added the following lines in the httpd.conf file: Alias /robots.txt /home/centos/sunlife/static/robots.txt Alias /favicon.ico /home/centos/sunlife/static/favicon.ico #Alias /media/ /path/to/mysite.com/media/ Alias /static/ /home/centos/sunlife/static/ <Directory /home/centos/sunlife/static> Require all granted </Directory> #<Directory /path/to/mysite.com/media> #Require all granted #</Directory> WSGIScriptAlias / /home/centos/sunlife/sunlife/wsgi.py <Directory /home/centos/sunlife/sunlife> <Files wsgi.py> Require all granted </Files> </Directory> While trying to access the ip, I am getting Forbidden You don't have permission to access / on this server. -
JavaScript / Django - Displaying Prices on the JQuery date picker calendar
I have implemented a JQuery UI date picker on my "booking" website. I can choose from and to dates, and submit them and make a reservation for the apartment. What I would like to do next is to display prices for each individual day. I also need to be able to do "price-ranges", so one price from date 01-05, another price from 06-12, etc. I'm doing this in Django, as a task I was given, only the calendar is JS, which I don't have much experience with. In the Django backend there is a model where I store the "start_price_date and "end_price_date", aswell as the "price". When I query the backend in JS, this is what I get : 0: "3-10-2019" 1: "999" 2: "4-10-2019" 3: "999" 4: "5-10-2019" 5: "999" 6: "20-10-2019" 7: "666" 8: "21-10-2019" 8: "666" 10: "22-10-2019" 11: "666" So, I get back the dates, and the price for each date. I am having trouble implementing this in the JQuery calendar since I have little to no experience with JS/JQuery. I have tried googling, and went over a few stack overflow posts, tried a few functions but I honestly dont know what I'm doing, this is … -
Django exclude field from all queries
I am running Django on Heroku with zero-downtime feature. This means that during deployment there are two version of code running (old and new) on the same database. That's why we need to avoid any backward incompatible migrations. It there a possibility to exclude a field from Django query on a given model? Let say we have a model (version 1): class Person(models.Model): name = models.CharField() address = models.TextField() In some time in the future we want to move address to the separate table. We know that we should not delete a field for older code to work so Person model may look like (version 2): class Person(models.Model): name = models.CharField() address = models.ForeignKey(Address) _address = models.TextField(db_name='address') This way if old code will query for address it will get it from Person table even if database has been migrated (it will be an old value, but let assume thats not a big issue). How now I can safetly delete _address field? If we will deploy version 3 with _address field deleted then code for version 2 will still try to fetch _address on select, even if it's not used anywhere and will fail with "No such column" exception. Is there … -
Nested For Loop In JINJA for django
My problem is that When I run, Web Page Shows Blank Page, Is there any other way to access Nested For loop for this kind of problem.? This Is my Template. {% for j in N %} {% for k in j %} <h1>{{ k.Name }}</h1> {% endfor %} {% endfor %} and this is view.py post1 = [ { "Name":"Mustafa" } ] post2 = [ { "Name":"Abbas" } ] N = ["post1","post2"] def home_page(request): context = { "post1":post1, "post2":post2, "N":N } return render(request , 'app01/index.html',context) -
How to display sympy output in proper manner
I am very new to coding in Python and using the django. My question: is it possible to get the input-format of an output I get from previous calculations? For example, if I obtain an output is like x**2 how can I get x^2 automatically? https://i.imgur.com/Screenshot_2.png" -
Django unknown column error when trying to get a model objects
I'm trying to set up a web-app that modify an existing MySQL database using Dajngo, the model for my table below was generated via Django inspectdb: class BaseCase(models.Model): base_case_name = models.TextField(blank=True, null=True) version = models.TextField(blank=True, null=True) default = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'base_case' and here is an SQL of that base_case table in the database : CREATE TABLE `base_case` ( `base_case_name` tinytext, `version` tinytext, `default` bit(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; the problem is when I try to get the objects via Django ORM I keep getting this error django.db.utils.OperationalError: (1054, "Unknown column 'base_case.id' in 'field list'") -
SOLUTION to "programming error... relation ... does not exist" on Heroku Django
app is successfully deployed static index page works okay but pages that involve data do not work, giving "programming error ...relation ...does not exit" solution is: heroku run python manage.py migrate --run-syncdb -a appname redeploying didn't work delete all migration files locally, run makemigrations again locally, and push the generated migration files to git: didn't work - what works is this: heroku run python manage.py migrate --run-syncdb -a appname i learned it from here: Relation does not exist on Heroku hope it helps -
tabs link not working in the modal bootstrap with django
I am using django with bootstrap where i have a modal that includes tabs as links where each tab run a function and return the required data. The problem is that one of these tabs is not working... yet if i remove this tab and use it as a button the function works and return the correct values. Note the first 2 tabs run the same function where as the third one run another function. views.py def search(request): # search for person query = request.GET.get('search') print('query===>',query) try: if query != "": print("query is not empty!") try: c = cursor.execute('SELECT Person_.ID,Person_.Full_Name,Person_.Mothers_Name,Person_.Nickname_,Person_.Details,Person_.Address_,Person_.preferedActivity,Person_.Other_Activity,Person_.Other_Descriptive_Details,Person_.Status, Person_.Date_of_Birth,Person_.Place_of_Birth FROM Person_ WHERE Person_.ID LIKE ? or Person_.Full_Name LIKE ? or Person_.Mothers_Name like ? or Person_.Nickname_ LIKE ? or Person_.Details LIKE ? ORDER BY Person_.ID DESC',('%' + query + '%' ,'%' + query + '%', '%' + query + '%', '%' + query + '%', '%' + query + '%')) cc = c.fetchall() paginator = Paginator(cc,20) page_request_var = "page" print("page_request_var===>",page_request_var) page = request.GET.get(page_request_var) print("page====>",page) queryset = paginator.get_page(page) print("queryset=====>",queryset) return render(request,'pictureCard.html', {'c': cc,'countID':countID, 'countFullName': countFullName, 'countMother': countMother, 'countNickname':countNickname, 'countCritical':countCritical, "object_list":queryset, "page_request_var":page_request_var, }) else: print("Search value is empty") return redirect('../../') except pyodbc.DataError: print("DataError: Invalid value!") return redirect('../../') def getEvents(request,id): # search … -
How to serialize distinct queryset in django rest framework?
I have a model that handles Italian's VAT rates. There are three types of rate: 'Ordinaria', 'Ridotta', 'Minima' each type of rate can store multiple values according to a date. For example the current rate for ordinary VAT is 22% and has been set on the 1st oct 2013 but rates have changed during time and I need to store changes and to retrieve the three rates according to a specific date. The model to describe rates is called AliquoteIVA. I use a custom manager to retrieve the current rates as of today or by providing a specific date: class AliquoteIVAManager(models.Manager): def current(self, data): return self.filter(data__lte=data) \ .order_by('descrizione', '-data') \ .distinct('descrizione') class AliquoteIVA(models.Model): """ Modello delle aliquote IVA """ data = models.DateField( blank = False, ) descrizione = models.CharField( blank = False, max_length = 1, default = IVA.IVA_ORDINARIA, choices = IVA.IVA_TIPOLOGIA_CHOICES, ) aliquota = models.DecimalField( blank = False, null = False, default = '0', max_digits=19, decimal_places = 2, validators = [MinValueValidator(0.0)], ) objects = AliquoteIVAManager() def __str__(self): str_aliquota = "{0:.2f}".format(self.aliquota).replace('.', ',') return "IVA {descrizione} al {aliquota}% in vigore dal {data}".format( descrizione=self.get_descrizione_display(), aliquota=str_aliquota, data=self.data ) class Meta: ordering = ('-data', 'aliquota',) verbose_name = 'Aliquota IVA' verbose_name_plural = 'Aliquote IVA' I've tested … -
How can we setup Malayalam Language in Python Django?
I would like to create a Python Django website in "Malayalam". I think we can implement that using the Localisation method while enabling USE_I18N = True, USE_L10N = True in "settings.py". Is there any apps available for performing these? -
AttributeError: 'str' object has no attribute '_meta' / Python 3.6
File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 25, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 81, in check errors.extend(modeladmin.check()) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py", line 117, in check return self.checks_class().check(self, **kwargs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 526, in check errors.extend(self._check_list_filter(admin_obj)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 697, in _check_list_filter for index, item in enumerate(obj.list_filter) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 697, in for index, item in enumerate(obj.list_filter) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 740, in _check_list_filter_item get_fields_from_path(model, field) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\utils.py", line 500, in get_fields_from_path parent = get_model_from_relation(fields[-1]) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\utils.py", line 451, in get_model_from_relation return field.get_path_info()[-1].to_opts.model File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related.py", line 723, in get_path_info opts = self.remote_field.model._meta AttributeError: 'str' object has no attribute '_meta' I am facing this Error on python 3.6, I got this error when i migrate my django project -
Django: Cannot Update the Value of IntegerField
I have an IntegerField in my model and I try to update it in the admin page. No matter what value I input (e.g. 100, 200), the value is restored to 0 after saving it. models.py class inputform(models.Model): ... age = models.IntegerField('Age', blank=True, null=True) ... I have tried change the value via SQL in the database directly and it updated successfully. However, when I read it in the admin page and saved it without any change, the value restore to 0. Is there any wrong with my code? Thanks! -
Making field required = False on ModelForm
I've got a model of UserCoupon that a user can create and edit. Upon edit, I only want them to be able to edit the 'code' field on the instance of UserCoupon if there are no orders associated with that code. When there are orders associated with that coupon code, rather than outputting {{form.code}} on the edit coupon form, I'm outputting {{form.instance.code}}. When the user attempts to submit the form, I get an error saying that the field is required. How can I make this field not required or otherwise address this situation so that the user can submit the form when one of the fields defined for the model form shows up in the template as an instance of the field rather than an input box? Models.py class UserCoupon(models.Model): code = models.CharField(max_length=15, unique=True) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) forms.py class EditUserCouponForm (forms.ModelForm): class Meta: model = UserCoupon def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(EditUserCouponForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(EditUserCouponForm, self).clean() template {% if coupon_order_count > 0 %} {{form.instance.code}} {% else %} {{form.code}} {% endif %} Thanks! -
Django Unittest mockset patching doens't always work
I wrote the following unit test, which succeeds when I run it individually via the VSCode IDE / unit test browser. api\test\test_views.py: class ProductListViewTest(APITestCase): def test_get_products(self): mock_products = MockSet() mock_products.add(MockModel( mock_name='e1', prod_id='1') # hit the API endpoint client = APIClient() with patch('api.models.Product.objects', mock_products): response = client.get(reverse('product-list')) # expected result expected = [ { 'prod_id': '1', } ] serialized = ProductSerializer(expected, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serialized.data) api\views.py: from api.models import Product class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer api\urls.py: # ... path('product/', views.ProductListView.as_view(), name='product'), # ... However, as soon as I run it by python manage.py test, it fails, because response.data is an empty array - which probably means it is quering the empty test_ database and not the patched object. I tried to patch with patch('api.views.Exception.objects', mock_products): instead of with patch('api.models.Exception.objects', mock_products): but then the unittest fails in both cases. -
inilah 13 cara menggugurkan kandungan yang paling banyak di minati 082226222691
Info Konsultasi Wa : 082226222691, Inilah 12 Obat aborsi di jakarta Yang Paling Banyak Di Minati, Jual 13 Jenis Dan Merk Obat Aborsi Di Kota Bandung Provinsi Jawa Barat, klinik terpecaya untuk : menggugurkan kandungan , Tersedia juga : jamu penggugur kandungan, cara menggugurkan kandungan dengan paracetamol, cara menggugurkan kandungan 1 bulan, obat terlambat haid , cara menggugurkan kehamilan , penggugur kandungan, semua akan teratasi jika anda memesan obat, janin 1 bulan, cara menggugurkan , cara mengatasi telat haid, cara menggugurkan kandungan 100 berhasil, Kami Menberikan Pelayanan Semaksimal Mungkin Dengan Pengalaman Kami, cara gugurin kandungan, cara menggugurkan janin, cara menggugurkan hamil muda, cara menggugurkan kandungan 2 bulan, telat datang bulan 1 bulan, cara gugurkan kandungan, cara menggugurkan kandungan 2 minggu, makanan penggugur kandungan, penyebab telat datang bulan selama 2 bulan, cara aborsi, sitotek, cara menggugurkan kandungan 4 bulan, Mengggurkan kandungan alias aborsi sering diidentikkan dengan mengakhiri kehamilan yang tidak diinginkan cara menggugurkan kandungan usia 1 bulan, Jangan Untuk Juga Menonton video aborsi, cara menggugurkan kandungan dengan cepat, cara menggugurkan bayi, cara menggugurkan kandungan 1 minggu, kandungan 3 bulan, cara menggagalkan kehamilan, cara menggugurkan kandungan secara tradisional, Jangan Membeli Produk Di Warung-Warung Untuk Obat Telat Bulan Anda, kenapa bodrex dan sprite … -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use order_items.set() instead
I have Ordel model in my project models.py class Order(models.Model): order_id = models.CharField(max_length=50, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='orders') total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='order_items') quantity = models.PositiveIntegerField(null=True, blank=True, default=1) serializers.py class OrderSerializer(serializers.ModelSerializer): order_items = serializers.StringRelatedField(many=True, required=False) class Meta: model = Order fields = ['id', 'user', 'total', 'order_items'] def create(self, validated_data): return Order.objects.create(**validated_data) class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['id', 'order', 'product', 'quantity'] finally views.py class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer def perform_create(self, serializer): try: purchaser_id = self.request.data['user'] user = User.objects.get(pk=purchaser_id) except: raise serializers.ValidationError( 'User was not found' ) cart = user.cart for cart_item in cart.items.all(): if cart_item.product.inventory - cart_item.quantity < 0: raise serializers.ValidationError( 'We do not have enough inventory of ' + str(cart_item.product.name) + \ 'to complete your purchase. Sorry, we will restock soon' ) total_aggregated_dict = cart.items.aggregate(total=Sum(F('quantity')*F('product__price'),output_field=FloatField())) order_total = round(total_aggregated_dict['total'], 2) order = serializer.save(customer=user, total=order_total) order_items = [] for cart_item in cart.items.all(): order_items.append(OrderItem(order=order, product=cart_item.product, quantity=cart_item.quantity)) cart_item.product.available_inventory -= cart_item.quantity cart_item.product.save() OrderItem.objects.bulk_create(order_items) cart.items.clear() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) when send Post request to the url /orders/ it throws error …